cdalley
cdalley

Reputation: 3

Copying files if creation date is greater than last backup

I am having some issues with a script I have written - I am trying to get this portion of the script to loop through and find any files where the creation date is greater than the last time we ran a backup.

$auditDate = (Get-Date).AddDays(0)
$lastAudit = Get-Content $auditLog | Select-Object -last 1
$desDir = "E:\Backup\"
$srcDir = "C:\\Data"

foreach ($file in Get-ChildItem $srcDir)
{
    if ($file.CreationTime.Date.toString("dd/MM/yyyy") -gt $lastAudit)
    {  
        Copy-Item $file.FullName $desDir
    }
    {
    }
}

At the moment when I run the script I am getting all the files in the folder copied across.

Any ideas?

Upvotes: 0

Views: 12609

Answers (1)

StephenP
StephenP

Reputation: 4081

Part of the problem may be from comparing dates as strings. For example:

#April 12,2011 is greater than July 7, 2014
"12/04/2011" -gt "07/07/2014"
True
#July 7, 2014 is not greater than June 8, 2014
"07/07/2014" -gt "08/06/2014"
False

See if this helps at all

#Not used in your example but why add 0 days to now?
$auditDate = [DateTime]::Now
$lastAudit = Get-Content $auditLog | Select-Object -last 1
$desDir = "E:\Backup\"
$srcDir = "C:\Data"
#Create a datetime object
$lastAuditDate = [DateTime]::Now
#Parse the retrieved timestamp to a datetime object
#note there is an overload for this method if you need to specify culture
if([DateTime]::TryParse($lastAudit,[ref]$lastAuditDate)){
    #Date parsed successfully get all files newer than the parsed date and copy them
    #To exclude directories add a -File to Get-ChildItem
    #To recurse through subdirectories add a -Recurse
    Get-ChildItem $srcdir | Where-Object {$_.CreationTime.Date -gt $lastAuditDate} | ForEach-Object {Copy-Item $_.FullName $desDir}
}else{
    Write-Error "Failed to parse retrieved date"
}

Note if this directory is large, using a foreach-object with a nested if statement may be faster than a where-object.

Upvotes: 3

Related Questions