Create Path consisting of to Variables and a Prefix

rated by 0 users
This post has 13 Replies | 2 Followers

Top 75 Contributor
Posts 41
janfreiburghaus79 Posted: 12-30-2011 4:20 AM

Hello

I want to creat the following new Directory with the New-Item Cmdlet. The name of the directory is created by the Prefix 2 Variables and "_" => "Archive_" + $ArchivDirectory + "_" + $Date).

 

I get always get Archive_\LOGS\_111230 (separated by "\")

instead of a Directory Name like "Archive_LOGS_111230"

I cant resolve this issue alone.

Can someone help me out?

Get-ChildItem d:\Logs\ -include *.log -recurse | Where-Object {!$_.PsISContainer} |
foreach{
$ArchiveDirectory = Split-Path d:\Logs\ -NoQualifier  #this gives me "\Logs\"
$ArchivePath = New-Item -type container  -path ("Archive_" + $ArchiveDirectory + "_" + $Date) -type directory -Force
$_ | Copy-Item -Destination $ArchivePath -Force

 

 

Thanks

Top 75 Contributor
Posts 41

I tried also this :


$ArchiveDirectory = Split-Path d:\LOGS\ -NoQualifier
$targetpath = "\\omsrv01\users\jf\Backup\"

cd $targetpath

mkdir ("Archive_" + $ArchiveDirectory + "_" + $Date)

 

But get this:

 


    Verzeichnis: \\omsrv01\users\jf\Backup\Archive_\LOGS


Mode                LastWriteTime     Length Name                                                                                              
----                -------------     ------ ----                                                                                              
d----        30.12.2011     11:44            _20111230_0851

 

What did i forget to do in order to get the directory named

" Archive_LOGS_20111230_0851"

Top 75 Contributor
Posts 41

I could resolve it by my own:

 

#PARAMETER
$days = (Get-Date) - (New-TimeSpan -Days 40)
$source = "D:\Logs\"
$formats = "*.txt", "*.csv"
$target = "D:\BACKUP\"
$ArchiveDirectory = Split-Path $source -NoQualifier
$targetpath = "\\omsrv01\users\jf\Backup\"
$ArchivePrefix = "Archiv_"
$date = Get-Date -format yyyyMMdd_HHmm

$ArchiveDirectoryName = $ArchivePrefix + $ArchiveDirectoy + $date

Top 75 Contributor
Posts 41

unfortunately it gave my only back

 

Archive_111230_1309

 

instead of Archive_LOGS_111230_1309

 

What is wrong?

 

I have made a typing error but even if write it right it gives me something like a path and not a DirectoryName

Top 10 Contributor
Posts 640

You had a typo in the last line. This works fine for me:

 

$days = (Get-Date) - (New-TimeSpan -Days 40)

$source = "D:\Logs\"

$formats = "*.txt", "*.csv"

$target = "D:\BACKUP\"

$ArchiveDirectory = Split-Path $source -NoQualifier 

$targetpath = "\\omsrv01\users\jf\Backup\"

$ArchivePrefix = "Archiv_"

$date = Get-Date -format yyyyMMdd_HHmm

$ArchiveDirectoryName = $ArchivePrefix + $ArchiveDirectory + $date

Write $ArchiveDirectoryName

The result is Archive_\Logs\20111230_0734. That's because $ArchiveDirectory contains "\Logs\" - you might consider outputting the contents of your variables as you change them, so that you can see what's actually in them. I think you were assuming $ArchiveDirectory would contain 'Logs' which isn't the case.

If you don't want the \ in there, you could use the -replace operator to replace "\" with "" and remove the backslashes.

 

Top 75 Contributor
Posts 41

Perfect!

 

But i figured out when i use -Leaf instead of -NoQualifier

 

like so

$ArchiveDirectory = Split-Path $source -Leaf

 

As a result i get also "Logs" without the slash "\".

Thanks for the tip to use write command to validate variable contents

 

Top 75 Contributor
Posts 41

I have one more question

 

Is it possible to pass the argument (in this case a UNC path) without using " " from the command line?

 

Or are you forced to enclose a UNC path in double quotes ""?

param([string]$targetpath,

[int]$age

)

 

$targetpath = \\srv01\backup\

$age = 30

 

powershell.exe -noexit c:\temp\script.ps1 -argument1 \\srv01\backup\, -argument2 30

 

Top 10 Contributor
Posts 640

You only need the quotes if the value contains a space, tab, or other whitespace, or  comma. In your example, I'm not sure why the comma is there. To PowerShell, that would be illegal - it indicates a list of values, and you haven't provided a second value.

Also, your usage isn't exactly correct. PowerShell.exe doesn't have an "-argument1" or "-argument2" parameter. I understand that those are parameters you intend to pass to your script, but that isn't quite the correct syntax when you're calling Powershell.exe.

powershell.exe -noexit -command "c:\script -arg1 val -arg2 val2"

Is probably more what you're looking for. There are other ways to accomplish this, though.

Top 75 Contributor
Posts 41

Nice tip but unfortunately i don't get the rigth result for some reason i don't know:

 

Here my last try:

$source = D:\Logs\BSC\

$ArchiveDirectory1 = $source 
$ArchiveDirectory2 = $ArchiveDirectory1 | split-path ($_.fullname -Replace "\", "") -NoQualifier





Write $ArchiveDirectory1
Write $ArchiveDirectory2

 

Result for $ArchiveDirectory2 is : $_.fullname -Replace "\", ""
instead of

"LogsBSC"

Where is the error??

Top 75 Contributor
Posts 41

this question reffers to your comment of 12-30-2011 9:30 AM

Top 10 Contributor
Posts 640

What's the goal, here? I don't think you've ever actually mentioned. What input are you starting with, and what's the desired output?

Top 75 Contributor
Posts 41

The goal here is to create a backup/archive of old Logfiles of an application (maintaining the original structure and name of the sourcedirectory.

The User specifies a sourcepath ($ReferenceDirectory), the targetpath ($targetPath), the formats for example only *.txt or *.log Files($formats) and the age of the files to be archived ($RetentionDays) by passing the arguments from the command line or batchfile:

 

The Archivedirectory should have the same structure/name as the sourcedirectory but whitout backslashes.

for Example

$ReferenceDirectory = d:\Logs\BSC\

the

$Archivedirectory should be = Logs_BSC

 

and $ArchiveDirectoryName = Archive_Logs_BSC_20120104 (consists of a prefix, variable Archvivedirectory and the date

 

Command:

#powershell.exe -noexit file .\scriptname Argument1 Argument2

#Param(
#[string]$ReferenceDirectory,    (Mandatory)
#[string]$targetPath,               (Mandatory)
#[string]$formats,                  (Mandatory)
#[int]$RetentionDays,               (Mandatory)
#[switch]$Recurse                    (Mandatory 3 Levels of Recursivity)      
#)


#Script continuation
$ErrorActionPreference = "SilentlyContinue"

#Module ZIP Creation
Import-Module pscx

#Set Time
Set-Date -Date (Get-Date)


#PARAMETER + VARIABLEN

$RetentionDays = 30 #alternativ => $age = (Get-Date) - (New-TimeSpan -Days 30)
$ReferenceDirectory = "D:\Logs\BSC\"
$targetPath = "\\opm-w26\BACKUP\"
$formats = "*.txt", "*.csv"
$ArchiveDirectory = Split-Path $ReferenceDirectory  -Leaf #Wird für ArchiveDirectoryName benötigt
$ArchivePrefix = "Archive_"
$date = Get-Date -format yyyyMMdd_HHmm

# Get all the files from the ReferenceDirectory
$FilestoArchive = Get-ChildItem $ReferenceDirectory -Include $formats -Recurse -errorAction Silentlycontinue  | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$RetentionDays) }
             

            
#Parse path=> $ArchiveDirectoryName
$ArchiveDirectory = Split-Path $ReferenceDirectory -Leaf  #needed to Build ArchiveDirectoryName
$ArchiveDirectoryName =  $ArchivePrefix + $ArchiveDirectory + "_" + $date

#ArchiveDirectory to be copied
$completeArchivePath = $targetpath + $ArchiveDirectoryName

#Zip (Function Archive with compressing)
$Level=1

Import-Module pscx
Write-Zip -Path $filestoArchive -outputpath ("$completeArchivePath" + ".zip") -level $Level -Quiet

#Log of archived Files
$backup_log = Dir -Recurse $filestoArchive | out-File -Filepath "$targetpath\backup_log.txt" -Encoding utf8 -Force


#Purge archived Files

$FilestoArchive | Remove-Item -Force -recurse -ErrorAction SilentlyContinue



I also have to create 3 different functions from which the user can chooose.

Function DeleteLogs

Function ArchiveLogs

Function ArchiveLogsand Compress

 

I hope now the goal is clear.

I appreciate your help

      
       


Top 75 Contributor
Posts 41

I have now built my function (called Archiver) but i dont get it how to pass params / Arguments from the batchfile to the function

 



#PARAMETER
$RetentionDays = 30
$ReferenceDirectory = "D:\Logs\"
$targetPath = "D:\BACKUP\"
$formats = "*.txt", "*.csv"
$variableFunction = 2

#FIX Variables
$ArchiveDirectory = Split-Path $ReferenceDirectory  -Leaf #need for building the archivedirectoriesname
$ArchivePrefix = "Archive_"
$date = Get-Date -format yyyyMMdd_HHmm
$Level=1 #Compression Level

#Fetch Files and Buid ArchiveDirectory
# Get all the files from the ReferenceDirectory
$FilestoArchive = Get-ChildItem $ReferenceDirectory -Include $formats -Recurse -errorAction Silentlycontinue  | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$RetentionDays) }         

#parse path => $ArchiveDirectoryName
$ArchiveDirectory = Split-Path $ReferenceDirectory -Leaf  #needed for building the Archivedirectoryname
$ArchiveDirectoryName =  $ArchivePrefix + $ArchiveDirectory + "_" + $date

#ArchiveDirectory to be copied
$completeArchivePath = $targetpath + $ArchiveDirectoryName

function Archiver {
$RetentionDays = 30 #alternativ => $age = (Get-Date) - (New-TimeSpan -Days 30)
$ReferenceDirectory = "D:\Logs\"
    $targetPath = "D:\BACKUP\"
    $formats = "*.log", "*.txt"
$variableFunction = 2
$Level = 9
#Param(
#    [string]$ReferenceDirectory,   
#    [string]$targetPath,
#    [string]$formats,
#    [int]$RetentionDays,
#    [switch]$variableFunction
#)
    switch ($variableFunction) {

    1 {$cutoff  = (Get-Date).AddDays(-$RetentionDays)
        Get-ChildItem -Path $ReferenceDirectory -Include $formats  -Recurse |
        Where-Object {-not $_.PsIsContainer -and $_.LastWriteTime -gt $cutoff } |
        Remove-Item -WhatIf }
   
    2    {Import-Module pscx
        Write-Zip -Path $filestoArchive -outputpath ("$completeArchivePath" + ".zip") -level $Level -Quiet
        #Log der Archivierten Files
        $backup_log = Dir -Recurse $filestoArchive | out-File -Filepath "$targetpath\backup_log.txt" -Encoding utf8 -Force}

    3 {$cutoff  = (Get-Date).AddDays(-$RetentionDays)
        Get-ChildItem -Path $ReferenceDirectory -Include $formats -Recurse |
        Where-Object { -not $_.PsIsContainer -and $_.LastWriteTime -gt $cutoff } |
        Copy-Item -container -Destination $targetPath
        $filestoArchive | Remove-Item -WhatIf
        #Log der Archivierten Files
        $backup_log = Dir -Recurse $filestoArchive | out-File -Filepath "$targetpath\backup_log.txt" -Encoding utf8 -Force }


    } #end Function
}

 

 

How can i pass for example 1 from the commandline to the function

 

powershell.exe -noexit -file .\function_Archiver.ps1 -referencedirectory d:\Logs\BSC\ -targetpath \\omsrv01\BACKUP -formats *.txt, *.log" -Retentiondays 30  -variableFunction 3

 

Somehow it wont work. I know that it is possible to leave out the "-parameter" keyword by using a positional parameter . But what i Dont know is how to creat a positional Param?

 

like this?

 

param (
[parameter(Position=0,
   Mandatory=$true,
   [string]$ReferenceDirectory

[parameter(Position=1,
   Mandatory=$true,
   [string]$targetpath

 

Top 10 Contributor
Posts 640

Sort of. 

[CmdletBinding()]
param(
  [Parameter(Mandatory=$True,Position=1)]
  [string]$Reference,
  [Parameter(Mandatory=$True,Position=2)]
  [string]$target
)

You've got the syntax slightly wrong. You can also omit the [Parameter()] business completely. All parameters are positional by default - you don't need to declare them that way specifically.

Page 1 of 1 (14 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.