2012-09-10 53 views
1

我的問題是使用Powershell。 我有一個非常大的文件夾。內幕人士約有1 600 000個子文件夾。 我的任務是清除超過6個月的所有空文件夾或文件。 我寫了用foreach循環,但PowerShell和它開始之前,需要年齡 - >使用Powershell檢查很多文件夾

...

foreach ($item in Get-ChildItem -Path $rootPath -recurse -force | Where-Object -FilterScript { $_.LastWriteTime -lt $date }) 
{ 
# here comes a script which will erase the file when its older than 6 months 
# here comes a script which will erase the folder if it's a folder AND does not have child items of its own 

...

的問題:我的內部存儲空間已滿(4GB)我不能正常工作了。 我的猜測:PowerShell加載所有1 600 000個文件夾,只有在它開始過濾它們。

有沒有可能防止這種情況發生?

回答

0

你是對的,所有的1.6M文件夾,或者至少是對它們的引用,都被一次加載。最佳做法是過濾左邊的&格式; IOW,如果可能(如果可能的話,gci不支持日期過濾器AFAICT)在您點擊Where-Object之前刪除這些文件夾。另外,如果你把東西留在管道中,你會使用更少的內存。

以下將$items限制爲只符合您的條件的文件夾,然後對這些對象執行循環。

$items = Get-ChildItem -path $rootpath -recurse -force | ?{ $_.LastWriteTime -lt $date } 
foreach ($item in $items) { 
# here comes a script which will erase the file when its older than 6 months 
# here comes a script which will erase the folder if it's a folder AND does not have child items of its own 
} 

或進一步精簡:

function runScripts { 
    # here comes a script which will erase the file when its older than 6 months. Pass $input into that script. $input will be a folder. 
    # here comes a script which will erase the folder if it's a folder AND does not have child items of its own Pass $input into that script. $input will be a folder. 
} 
Get-ChildItem -path $rootpath -recurse -force | ?{ $_.LastWriteTime -lt $date }|runScripts 

在最後這種情況下,你使用runScripts作爲使用流水線對象可在($input)操作參數的函數,所以你可以通過管道發送所有內容,而不是使用那些中間對象(這會消耗更多的內存)。

+0

謝謝我只是在較小的環境中測試它。 (106 000個文件夾) 我的原始sk took大約需要73s。 隨着你的修改(簡化)它只需要我51秒。 謝謝! – user1660311

+0

哦,內存問題似乎也解決了:) – user1660311

相關問題