Let’s say you’ve got a scheduled PowerShell task running to pull a list of files created on a certain date. You might try accomplishing such a feat with this code:
$datePreserveWeek = (Get-Date).AddDays(-7) Get-ChildItem -Path "C:\Backups" -Filter *.bak | where { $_.CreationTime -eq $datePreserveWeek }
Unfortunately, even if you have files that were created exactly 7 days ago, you will most likely get nothing back from this call. That’s because CreationTime and $datePreserveWeek are DateTime objects, which store both date (year, month, day) and time (hour, minute, second) data. When you compare them with the -eq operator, unless the objects also happen to match exactly the specific time, you’ll get a $false result.
In the past, I’ve solved this problem with the following solution:
Get-ChildItem -Path "C:\Backups" -Filter *.bak | where { $_.LastWriteTime.Year -eq $datePreserveWeek.Year -and $_.LastWriteTime.Month -eq $datePreserveWeek.Month -and $_.LastWriteTime.Day -eq $datePreserveWeek.Day }
However, this method, while successful, apparently exposed my lack of knowledge about .NET’s DateTime class. MVP Shay Levi pointed out that the same thing can be accomplished with a bit less code!
Get-ChildItem -Path "C:\Backups" -Filter *.bak | where { $_.CreationTime.Date -eq $datePreserveWeek.Date }
The more you know…
Recent Comments