PowerShell Script: Copy to Backup folder\structure by LastWriteTime

What we’re doing here is grabbing the LastWriteTime, because unlike the creation time this usually doesn’t change. I start out by grabbing the $Source and $Target paths using the Global: Variable to pass it to the function.

We start the Function LastWriteTime_Backup by grabbing the source and target objects to compare them.

Because the $Source should be the newest files, we compare the $Source with the $Target. We grab either file by file or folder by folder. We compare the LastWriteTime with that same object in the $Target.

If the LastWriteTime is greater-than $Target file, then do the copy and tell me, but if its not less-than or equal, then do not do the copy and tell me that the file is the same. We can export this to a log, but if you run it by hand it will give you a Green for good and blue if the copy ran.

$Global:Source = "F:\Test2\*"
$Global:Target = "F:\Test\"

Function LastWriteTime_Backup{
# Get File info
$Src = Get-ChildItem $Global:Source -Recurse
$Dest = Get-ChildItem $Global:Target -Recurse

# Foreach File in $Global:Source
foreach ($file in $Src) 
{
$TargetLWT=Get-Item ($Global:Target + "\" + $file)
If ($file.LastWriteTime -gt $TargetLWT.LastWriteTime){
# Copy File to $Global:Target
Copy-Item -Path $file.Fullname -Destination $Global:Target -Force -Verbose
}
Else{Write-Host "$file is the same" -ForegroundColor Green
}}}
cls
LastWriteTime_Backup
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s