Powershell按文件最后修改時間刪除多余文件
1. 刪除目錄內多余文件,目錄文件個數大於$count后,按最后修改時間倒序排列,刪除最舊的文件。
Sort-Object -Property LastWriteTime -Descending 按照文件的最后修改時間倒序排列
Select-Object -Skip $count 跳過開頭的$count條數據,取剩余的數據
$count = 3 $filePathList = "E:\MySql\1", "E:\MySql\2", "E:\MySql\3" foreach($filePath in $filePathList) { $files = Get-ChildItem -Path $filePath | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip $count if ($files.count -gt 0) { foreach($file in $files) { Remove-Item $file.FullName -Recurse -Force } } }
2. 刪除目錄內所有文件修改時間超過timeOutDay的文件。
$timeOutDay = 30 $filePath = "H:\DataBackup\File\1", "H:\DataBackup\Database\2" $allFile = Get-ChildItem -Path $filePath foreach($file in $allFile) { $daySpan = ((Get-Date) - $file.LastWriteTime).Days if ($daySpan -gt $timeOutDay) { Remove-Item $file.FullName -Recurse -Force } }