File Management in Powershell

I’m looking to do the following in Powershell

1. Is a file that exists in a source folder more recent than a file in a target folder?
2. If it the file is more recent…copy it to the target folder, but before copying…
3. Back up the current version in the target folder, by appending a date to the file name.

Does a file exist?

test-path <filename>
This returns TRUE or FALSE if the file exists. If the file is in the current folder, then you can just list the file name, otherwise, the full path has to be included.

What is the file’s date and time?

The file date and time are properties of the file name, obtained via the Get-Item cmdlet.  We can assign these to a variable. Here I will compare file dates between two files that have the same name, but reside in different folders, one located along the default path, and one located on drive W.

$Sourcedate = (Get-Item w:myfile.csv).LastWriteTime
$TargetDate = (Get-Item myfile.csv).LastWriteTime
If ($Sourcedate = $Targetdate) {"True"}
If ($Sourcedate -lt $Targetdate) {"True"}
If ($Sourcedate -gt $Targetdate) {"True"}

Note (rather irritatingly….) that the usual comparison operators are different in Powershell.

=  -eq Equal
<> -ne Not Equal 
>= -ge Greater than or equal 
>  -gt Greater than
<  -lt Less than 
<= -le Less than or equal

 

Back up the target file

Having determined that the source file is newer than the target file, we now want to back up the target file, incorporating the date within the renamed filename.

myfile.csv
myfile0150505.csv
myfile.csv_5150505

Since we’ve used the functions for this in another post someplace,..

$ShortDate= $SourceDate | Get-Date -UFormat %Y%m%d

This returns the date in a short form:

20150505

Now append the date to the filename

$newfilename="myfile_"+$ShortDate+".csv"
Rename-Item myfile.csv $newfilename

This results in a file name of:

myfile_20150505.csv

Now we can do the copy from the source folder to the target.

Copy-Item  w:myfile.csv

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s