0
votes

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?

1
What's the format of $lastAudit? If it's not also dd/MM/yyyy, you'll never get a proper comparison. Comparing dates when formatted as strings will usually not work out - make them true date objects so they can be compared properly! - alroc
Sorry - Add-Content $auditLog $auditDate.ToString("dd/MM/yyyy") It is output to the same format! - cdalley
Don't ever compare dates as strings - compare them as dates! - alroc
To expand a little on alroc's comment, I came across the following weirdness. The following comparison wasnt working as expected for me; If((Get-Date $_.LastWriteTime) -gt (Get-Date $MaxJSDate)) { it was returning files where the LastWriteTime was equal to the MaxJSDate variable. When I printed out the two variables like so: Write-Host $_.LastWriteTime.GetType() Write-Host $MaxJSDate.GetType() I found they were both DateTime types. I rewrote the bad code as follows and now it works perfectly; If($_.LastWriteTime -gt $MaxJSDate) { - Sage

1 Answers

3
votes

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.