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)
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)
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.
This powershell script will show files older than 5 days, 10 hours, and 5 minutes. You can save it as a file with a .ps1
extension and then run it:
# You may want to adjust these
$fullPath = "c:\path\to\your\files"
$numdays = 5
$numhours = 10
$nummins = 5
function ShowOldFiles($path, $days, $hours, $mins)
{
$files = @(get-childitem $path -include *.* -recurse | where {($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)})
if ($files -ne $NULL)
{
for ($idx = 0; $idx -lt $files.Length; $idx++)
{
$file = $files[$idx]
write-host ("Old: " + $file.Name) -Fore Red
}
}
}
ShowOldFiles $fullPath $numdays $numhours $nummins
The following is a little bit more detail about the line that filters the files. It is split into multiple lines (may not be legal powershell) so that I could include comments:
$files = @(
# gets all children at the path, recursing into sub-folders
get-childitem $path -include *.* -recurse |
where {
# compares the mod date on the file with the current date,
# subtracting your criteria (5 days, 10 hours, 5 min)
($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins))
# only files (not folders)
-and ($_.psIsContainer -eq $false)
}
)
Test-Path
can do this for you:
Test-Path $fullPath -OlderThan (Get-Date).AddDays(-5).AddHours(-10).AddMinutes(-5)