当Remove-Item提示确认时,如何自动选择"否"?

Fab*_*ied 7 powershell

使用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"):
Run Code Online (Sandbox Code Playgroud)

如果我在非交互模式下运行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
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用-Recurse,Remove-Item就像我选择了"是"选项一样.我可以以某种方式进行,就像我选择了"否"选项一样吗?

(只是为了清晰:-Force和-Confirm:$false是不是我想要在这里.)

Jim*_*Jim 2

恕我直言,正确的答案是将 -ErrorAction 设置为 SilentlyContinue。那么你就不必有空的 try-catch 代码。

像这样:

PS C:\Users\<redacted>\Desktop\Temp> Remove-Item .\Test -ErrorAction SilentlyContinue
Run Code Online (Sandbox Code Playgroud)

更新:2023 年 6 月 26 日,PowerShell 7 更改了此行为,正如@Destroy666 指出的那样。您可以使用PoSH 7 中的三元运算符来使其成为单行程序并避免出现空的 try catch 块。

function TestIt () {
    $myFolder = 'C:\MyTestFolder'
    New-Item -Path $myFolder -ItemType Directory
    Set-Content -Path $myFolder\myfile.txt -Value 'My test text content'
    (Test-Path -Path $myFolder\*.*) ? $null : (Remove-Item -Path $myFolder)

    Get-ChildItem -Path $myFolder
}

TestIt
Run Code Online (Sandbox Code Playgroud)

运行此命令给出结果:

PS C:\> . .\test.ps1

    Directory: C:\

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----           6/26/2023  6:28 PM                MyTestFolder

    Directory: C:\MyTestFolder

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           6/26/2023  6:28 PM             22 myfile.txt

PS C:\>
Run Code Online (Sandbox Code Playgroud)