如何檢查Powershell查看$ fullPath中的文件是否早於「5天10小時5分鐘」?如何使用PowerShell檢查文件是否超過特定時間?
(由老了,我的意思如果創建或修改不晚於5天10小時5分鐘)
如何檢查Powershell查看$ fullPath中的文件是否早於「5天10小時5分鐘」?如何使用PowerShell檢查文件是否超過特定時間?
(由老了,我的意思如果創建或修改不晚於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
}
的原因,這作品是因爲減去兩個日期會給你一個時間跨度。時間跨度與標準運營商相當。
希望這會有所幫助。
這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)
}
)
Test-Path
能爲你做到這一點:
Test-Path $fullPath -OlderThan (Get-Date).AddDays(-5).AddHours(-10).AddMinutes(-5)
的-olderthan開關不PS2.0可用。不知道它什麼時候推出,但它在PS4.0中絕對可用。 – Mike