Remove-Item .\Test Confirm T-6ren">
gpt4 book ai didi

powershell - Remove-Item提示确认时如何自动选择 "No"?

转载 作者:行者123 更新时间:2023-12-04 12:41:25 66 4
gpt4 key购买 nike

使用 PowerShell 时 Remove-Item删除一个非空的目录,它会提示确认:

PS C:\Users\<redacted>\Desktop\Temp> Remove-Item .\Test

Confirm
The item at C:\Users\<redacted>\Desktop\Temp\Test 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"):

如果我在非交互模式下运行 powershell,则会出现错误:
Remove-Item : Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.
At line:1 char:1
+ Remove-Item .\Test
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Remove-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RemoveItemCommand

我知道我可以使用 -RecurseRemove-Item就像我选择了"is"选项一样继续。我可以以某种方式继续,就好像我选择了“否”选项一样?

(只是为了清楚起见: -Force-Confirm:$false 不是我想要的。)

最佳答案

在尝试删除目录之前,您可以使用 test-path 来确定目录是否为空:

if (-not (Test-Path .\Test\*.*))
{ Try
{ Remove-Item .\Test -ErrorAction Stop }
Catch { Continue }
}

Try Catch 将处理任何错误

关于powershell - Remove-Item提示确认时如何自动选择 "No"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20243298/

66 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com