使用PowerShell清除文件夹

时间:2010-04-24 14:12:52

标签: powershell powershell-v2.0

我想在脚本运行后清除一些目录,删除当前目录中的某些文件夹和文件(如果存在)。最初,我构建了这样的脚本:

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

现在我已经在本节列出了很多项目,我想清理代码。我怎么能这样做?

附注:在脚本运行之前,项目已经清理,因为它们是从上一次运行中遗留下来的,以防我需要检查它们。

4 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分:0)

一种可能性

function ql {$args}

ql Folder1 Folder2 Folder3 File3 |
    ForEach {
        if(Test-Path $_) {
            Remove-Item $_
        }
    }

答案 3 :(得分:0)

# if you do not mind to have a few ignored errors
Remove-Item -Recurse -Force -ErrorAction 0 @(
    'Directory1'
    'Directory2'
    'File1'
)