30

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)

3 Answers 3

54

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.

22

Test-Path can do this for you:

Test-Path $fullPath -OlderThan (Get-Date).AddDays(-5).AddHours(-10).AddMinutes(-5)
1
  • The -OlderThan switch is not available in PS2.0. Not sure when it was introduced, but it's definitely available in PS4.0.
    – Mike
    Apr 3, 2016 at 15:09
10

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)

    }
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.