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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16613656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:15:40  来源:igfitidea点击:

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

.netpowershellpowershell-3.0

提问by pencilCake

How can I check in Powershellto see if a file in $fullPath is older than "5 days 10 hours 5 minutes" ?

如何检查Powershell以查看 $fullPath 中的文件是否早于“5 天 10 小时 5 分钟”?

(by OLD, I meanif it was created or modified NOT later than 5 days 10 hours 5 minutes)

旧的,我的意思是如果它是在不迟于 5 天 10 小时 5 分钟的时间内创建或修改的)

回答by x0n

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.

希望这可以帮助。

回答by Manuel Batsching

Test-Pathcan do this for you:

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

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

回答by chue x

This powershell script will show files older than 5 days, 10 hours, and 5 minutes. You can save it as a file with a .ps1extension and then run it:

此 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

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:

以下是有关过滤文件的行的更多详细信息。它被分成多行(可能不是合法的 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)

    }
)