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

…衆ロ難τιáo~ 提交于 2019-12-21 06:56:00

问题


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:


Test-Path can do this for you:

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



回答3:


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)

    }
)


来源:https://stackoverflow.com/questions/16613656/how-can-i-check-if-a-file-is-older-than-a-certain-time-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!