Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a file is older than a certain time with PowerShell?

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)

like image 905
pencilCake Avatar asked May 17 '13 16:05

pencilCake


People also ask

How do I determine the age of a file in PowerShell?

if (($fileObj. LastWriteTime) -lt (Get-Date). AddHours(-24)) {Write-Output "Old file"}

How do I compare dates in PowerShell?

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 .

How do I get LastWriteTime in PowerShell?

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.


2 Answers

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.

like image 169
x0n Avatar answered Sep 28 '22 00:09

x0n


Test-Path can do this for you:

Test-Path $fullPath -OlderThan (Get-Date).AddDays(-5).AddHours(-10).AddMinutes(-5) 
like image 28
Manuel Batsching Avatar answered Sep 28 '22 01:09

Manuel Batsching