2010-04-24 86 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