簡體   English   中英

如何使用PowerShell檢查文件是否超過特定時間?

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

如何檢查Powershell以查看$ fullPath中的文件是否超過“5天10小時5分鍾”?

OLD,我的意思是如果它是在5天10小時5分鍾之前創建或修改的)

這是一個非常簡潔但非常易讀的方法:

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

if (((get-date) - $lastWrite) -gt $timespan) {
    # older
} else {
    # newer
}

這樣做的原因是因為減去兩個日期會給你一個時間跨度。 時間跨度與標准運營商相當。

希望這可以幫助。

Test-Path可以為您完成此操作:

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

此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

以下是有關過濾文件的行的更多詳細信息。 它分為多行(可能不是合法的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)

    }
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM