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?
$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! - alrocIf((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