强制不抑制确认提示 - 从目录层次结构的任何级别按名称删除目录
Force not suppressing confirmation prompt - removal of directories by name from any level of a directory hierarchy
我已按照 PowerShell 脚本从我的其他项目中删除文件夹:
param([Parameter(Mandatory)][String]$path)
$directories = dir -Path $path -Directory -Recurse
foreach ($directory in $directories){
if ($directory.Name -eq "bin" -or $directory.Name -eq "obj"){
Remove-Item -Path $directory.FullName -Force -Confirm:$false
}
}
而且我用的时候总有提示
Confirm
The item at C:\Users\...\bin has children and the
Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want
to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
我知道将 -Recurse
添加到 Remove-Item
cmdlet 应该可以做到这一点,但这是多余的,因此代码可能会创建异常。那么如何取消该确认提示呢?
虽然我同意 -Confirm:$False
即使在没有 -Recurse
的情况下也应该禁止确认提示,但即使这样做了,删除仍然总是 递归 .
您真正的问题是使用 foreach
语句 ,它总是先创建目录列表 (即使您使用了 foreach ($dir in Get-ChildItem ...)
,因此可能会尝试访问在先前迭代中已删除的目录,作为先前删除的目录子树的一部分。
相比之下,直接使用 管道 Get-ChildItem -Recurse -Directory
通过不枚举子目录来优雅地处理递归枚举。之前的迭代已经删除:
param([Parameter(Mandatory)][String]$path)
# Note the use of the pipeline and the ForEach-Object cmdlet.
Get-ChildItem -Path $path -Directory -Recurse | ForEach-Object {
if ($_.Name -eq "bin" -or $_.Name -eq "obj"){
Remove-Item -Recurse -Force -Confirm:$False -LiteralPath $_.FullName
}
}
以上可以简化为:
Get-ChildItem -Path $path -Directory -Recurse -Include bin, obj |
Remove-Item -Recurse -Force -Confirm:$False
我已按照 PowerShell 脚本从我的其他项目中删除文件夹:
param([Parameter(Mandatory)][String]$path)
$directories = dir -Path $path -Directory -Recurse
foreach ($directory in $directories){
if ($directory.Name -eq "bin" -or $directory.Name -eq "obj"){
Remove-Item -Path $directory.FullName -Force -Confirm:$false
}
}
而且我用的时候总有提示
Confirm
The item at C:\Users\...\bin has children and the
Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want
to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
我知道将 -Recurse
添加到 Remove-Item
cmdlet 应该可以做到这一点,但这是多余的,因此代码可能会创建异常。那么如何取消该确认提示呢?
虽然我同意 -Confirm:$False
即使在没有 -Recurse
的情况下也应该禁止确认提示,但即使这样做了,删除仍然总是 递归 .
您真正的问题是使用 foreach
语句 ,它总是先创建目录列表 (即使您使用了 foreach ($dir in Get-ChildItem ...)
,因此可能会尝试访问在先前迭代中已删除的目录,作为先前删除的目录子树的一部分。
相比之下,直接使用 管道 Get-ChildItem -Recurse -Directory
通过不枚举子目录来优雅地处理递归枚举。之前的迭代已经删除:
param([Parameter(Mandatory)][String]$path)
# Note the use of the pipeline and the ForEach-Object cmdlet.
Get-ChildItem -Path $path -Directory -Recurse | ForEach-Object {
if ($_.Name -eq "bin" -or $_.Name -eq "obj"){
Remove-Item -Recurse -Force -Confirm:$False -LiteralPath $_.FullName
}
}
以上可以简化为:
Get-ChildItem -Path $path -Directory -Recurse -Include bin, obj |
Remove-Item -Recurse -Force -Confirm:$False