How can I check if a file is older than a certain

2019-04-03 10:13发布

问题:

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)

回答1:

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.



回答2:

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)

    }
)


回答3:

Test-Path can do this for you:

Test-Path $fullPath -OlderThan (Get-Date).AddDays(-5).AddHours(-10).AddMinutes(-5)