2010-04-24 85 views
10

我想通過從當前目錄中刪除某些文件夾和文件(如果它們存在)來清理腳本運行後的一些目錄。本來,我的結構是這樣的腳本:用PowerShell清理文件夾

if (Test-Path Folder1) { 
    Remove-Item -r Folder1 
} 
if (Test-Path Folder2) { 
    Remove-Item -r Folder2 
} 
if (Test-Path File1) { 
    Remove-Item File1 
} 

現在,我在這節中列出好幾個項目,我想清理代碼。我該怎麼做?

注意:這些項目在之前被清理,因爲它們從上次運行中遺留下來,以防我需要檢查它們。

回答

11
# if you want to avoid errors on missed paths 
# (because even ignored errors are added to $Error) 
# (or you want to -ErrorAction Stop if an item is not removed) 
@(
    'Directory1' 
    'Directory2' 
    'File1' 
) | 
Where-Object { Test-Path $_ } | 
ForEach-Object { Remove-Item $_ -Recurse -Force -ErrorAction Stop } 
+1

您可以通過刪除'$ _'直接管入'Remove-Item'。 – 2010-04-24 15:25:58

+1

好點(將輸入綁定到-Path參數)。事實上,我通常儘可能使用-LiteralPath(不太容易出錯),所以我提出這個版本仍然保留-LiteralPath。 – 2010-04-24 16:30:14

+0

偉大的片段,我一直在努力與「錯誤:目錄不是空的」比我想承認更長。 – 2014-04-12 22:48:30

0

一種可能性

function ql {$args} 

ql Folder1 Folder2 Folder3 File3 | 
    ForEach { 
     if(Test-Path $_) { 
      Remove-Item $_ 
     } 
    } 
0
# if you do not mind to have a few ignored errors 
Remove-Item -Recurse -Force -ErrorAction 0 @(
    'Directory1' 
    'Directory2' 
    'File1' 
) 
+0

我寧願沒有忽略的錯誤,因爲它們很容易地避免在這裏。 :) – 2010-04-24 15:26:54

+0

同意,它不適合您的情況,因爲您應該知道腳本繼續之前的問題。儘管如此,該版本還會在其他一些情況下使用,例如在腳本工作之後進行清理。 – 2010-04-24 16:45:43

1
Folder1, Folder2, File1, Folder3 | 
    ?{ test-path $_ } | 
     %{ 
      if ($_.PSIsContainer) { 
       rm -rec $_ # For directories, do the delete recursively 
      } else { 
       rm $_ # for files, just delete the item 
      } 
     } 

或者,你可以爲每種類型做兩個獨立的模塊。

Folder1, Folder2, File1, Folder3 | 
    ?{ test-path $_ } | 
     ?{ $_.PSIsContainer } | 
      rm -rec 

Folder1, Folder2, File1, Folder3 | 
    ?{ test-path $_ } | 
     ?{ -not ($_.PSIsContainer) } | 
      rm 
+1

事實證明'Remove-Item -r'適用於文件夾和文件。 – 2010-04-24 15:19:33

+0

@ 280Z28酷!我不知道。 – 2010-04-24 16:00:40