使用PowerShell清除文件夹

Sam*_*ell 10 powershell powershell-2.0

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

if (Test-Path Folder1) {
  Remove-Item -r Folder1
}
if (Test-Path Folder2) {
  Remove-Item -r Folder2
}
if (Test-Path File1) {
  Remove-Item File1
}
Run Code Online (Sandbox Code Playgroud)

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

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

Rom*_*min 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 }
Run Code Online (Sandbox Code Playgroud)