本來想用批處理的,想想算時間太麻煩了……
立馬安裝PowerShell看協助文檔,裡面有個例子:
以下命令尋找 Program Files 檔案夾中上次修改日期晚於 2005 年 10 月 1 日並且既不
小於 1 MB 也不大於 10 MB 的所有可執行檔(測試發現沒法運行-_-!):
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object `
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) `
-and ($_.Length -le 10m)}
改了一下成為下面的,以刪除D:\test及子目錄裡10天前建立的檔案為例,測試請謹慎!
因為內容太長顯示成多行,實際上是一行。用“`”字元作為延續符(雙引號內的,是重
音符不是單引號),相當於vbs的“_”,它告訴Windows PowerShell下一行是延續部分,
它在整行如果不換行就無法置於庫中這種情況下有用。只允許將運算式作為管道的第一
個元素。
一行命令取得到期檔案清單:
Get-ChildItem -Path D:\test -Recurse -ErrorAction:SilentlyContinue | `
Where-Object -FilterScript {(((get-date) - ($_.CreationTime)).days -gt 10 `
-and $_.PsISContainer -ne $True)} | Select-Object FullName
一行命令刪除到期檔案:
Get-ChildItem -Path D:\test -Recurse -ErrorAction:SilentlyContinue | `
Where-Object -FilterScript {(((get-date) - ($_.CreationTime)).days -gt 10 `
-and $_.PsISContainer -ne $True)} | Remove-Item
一行命令刪除到期檔案(包括刪除唯讀、隱藏):
Get-ChildItem -Path D:\test -Force -Recurse -ErrorAction:SilentlyContinue | `
Where-Object -FilterScript {(((get-date) - ($_.CreationTime)).days -gt 10 `
-and $_.PsISContainer -ne $True)} | Remove-Item -Force
當然,可以用別名簡寫命令。
或者先在Types.ps1xml檔案裡找到System.IO.FileInfo,增加Age成員:
<Name>System.IO.FileInfo</Name>
<Members>
<ScriptProperty>
<Name>Age</Name>
<GetScriptBlock>
((get-date) - ($this.creationtime)).days
</GetScriptBlock>
</ScriptProperty>
</Members>
添加的內容是從<ScriptProperty>到</ScriptProperty>,修改後以後不用再加。
指令碼內容:
ForEach ($file in Get-ChildItem D:\test\* -Force -Recurse `-ErrorAction:SilentlyContinue) { if (($file).Age -ge 10 -and $file.PsISContainer -ne $True) {$file.Delete()} }
這裡不能使用{Remove-Item -Force "$file"}
指令碼副檔名是.ps1,副檔名裡的是數字1。
-gt是大於,-ge是大於或等於,其他看協助。
如果PSIsContainer屬性為真那意味著處理的是檔案夾而不是檔案。
-Force是包括唯讀、隱藏等系統檔案,用了它之後最好用-ErrorAction。
-ErrorAction:SilentlyContinue作用是不顯示錯誤繼續執行指令碼,比如遞迴時遇到
System Volume Information等無許可權進入的目錄就會出錯。
尋找指定日期前建立的檔案:
Get-ChildItem -Path D:\test -Force -Recurse -ErrorAction:SilentlyContinue | `Where-Object -FilterScript {($_.CreationTime -gt "2011-01-01") -and `($_.PsISContainer -ne $True)} | Select-Object FullName
尋找指定日期前修改的檔案:
Get-ChildItem -Path D:\test -Force -Recurse -ErrorAction:SilentlyContinue | `Where-Object -FilterScript {($_.LastWriteTime -gt "2011-01-01") -and `($_.PsISContainer -ne $True)} | Select-Object FullName
如果要刪除,Select-Object FullName改成Remove-Item -Force
指定日期的用批處理還是很方便,如果要指定刪除N天前的舊檔案就麻煩了點,
下面的樣本是用bat刪除指定日期修改過的檔案。注意是修改,不是建立,只
有dir /tc才能查看到檔案建立時間,預設dir都是dir /tw
發信人: nwn (Lie), 信區: DOS
標 題: Re: (for命令)大量刪除某一時間段內建立的檔案?
發信站: 水木社區 (Sat Jun 7 08:39:39 2008), 站內
@echo offcd /d 你的目錄for %%f in (*) do if "%%~tf" gtr "2008-04-01" del "%%f"
如果要包含子目錄,使用 for /r . %%f in ....
【 在 justzhou (玉樹臨風) 的大作中提到: 】
: 比如要刪除某目錄下2008-04-01後建立的所有的檔案。。