How can I check in Powershell to see if a file in $fullPath is older than "5 days 10 hours 5 minutes" ?
(by OLD, I mean if it was created or modified NOT later than 5 days 10 hours 5 minutes)
if (($fileObj. LastWriteTime) -lt (Get-Date). AddHours(-24)) {Write-Output "Old file"}
Comparing Dates PowerShell knows when a date is “less than” (earlier than) or “greater than” (later than) another date. To compare dates, simply create two DateTime objects using PowerShell Get Date command or perhaps by casting strings with [DateTime] and then using standard PowerShell operators like lt or gt .
Use the Get-ChildItem LastWriteTime attribute to find the list of files with lastwritetime. Get-ChildItem in the PowerShell gets one or more child items from the directory and subdirectories.
Here's quite a succinct yet very readable way to do this:
$lastWrite = (get-item $fullPath).LastWriteTime $timespan = new-timespan -days 5 -hours 10 -minutes 5 if (((get-date) - $lastWrite) -gt $timespan) { # older } else { # newer }
The reason this works is because subtracting two dates gives you a timespan. Timespans are comparable with standard operators.
Hope this helps.
Test-Path
can do this for you:
Test-Path $fullPath -OlderThan (Get-Date).AddDays(-5).AddHours(-10).AddMinutes(-5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With