10

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

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

既然我在本节中列出了很多项目,我想清理一下代码。我该怎么做?

旁注:这些项目在脚本运行之前被清理,因为它们是上次运行留下的,以防我需要检查它们。

4

4 回答 4

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 }
于 2010-04-24T15:03:54.177 回答
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
于 2010-04-24T14:55:58.120 回答
0

一种可能

function ql {$args}

ql Folder1 Folder2 Folder3 File3 |
    ForEach {
        if(Test-Path $_) {
            Remove-Item $_
        }
    }
于 2010-04-24T14:42:55.547 回答
0
# if you do not mind to have a few ignored errors
Remove-Item -Recurse -Force -ErrorAction 0 @(
    'Directory1'
    'Directory2'
    'File1'
)
于 2010-04-24T14:50:44.373 回答