如何使用PowerShell检查文件是否超过特定时间?

pen*_*ake 20 .net powershell powershell-3.0

如何检查Powershell以查看$ fullPath中的文件是否超过"5天10小时5分钟"?

(OLD,我的意思是如果它是在5天10小时5分钟之前创建或修改的)

x0n*_*x0n 43

这是一个非常简洁但非常易读的方法:

$lastWrite = (get-item $fullPath).LastWriteTime
$timespan = new-timespan -days 5 -hours 10 -minutes 5

if (((get-date) - $lastWrite) -gt $timespan) {
    # older
} else {
    # newer
}
Run Code Online (Sandbox Code Playgroud)

这样做的原因是因为减去两个日期会给你一个时间跨度.时间跨度与标准运营商相当.

希望这可以帮助.


Man*_*ing 8

Test-Path 可以为您做到这一点:

Test-Path $fullPath -OlderThan (Get-Date).AddDays(-5).AddHours(-10).AddMinutes(-5)
Run Code Online (Sandbox Code Playgroud)


chu*_*e x 6

此PowerShell脚本将显示超过5天,10小时和5分钟的文件.您可以将其另存为带.ps1扩展名的文件,然后运行它:

# 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
Run Code Online (Sandbox Code Playgroud)

以下是有关过滤文件的行的更多详细信息.它分为多行(可能不是合法的powershell),以便我可以包含注释:

$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)

    }
)
Run Code Online (Sandbox Code Playgroud)