How do I automatically choose "No" when Remove-Item prompts for confirmation?
powershell
Solution
IMHO the correct answer is to set the -ErrorAction to SilentlyContinue. Then you don't have to have empty try-catch code.
Like this:
PS C:\Users\<redacted>\Desktop\Temp> Remove-Item .\Test -ErrorAction SilentlyContinue
UPDATE: 06-26-2023 PowerShell 7 changed this behavior as @Destroy666 pointed out. You can use the ternary operator in PoSH 7 to still make it a one liner and avoid empty try catch blocks.
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
Running this gives the results:
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:\>
Problem
When using PowerShell's `Remove-Item` to remove a directory that is not empty, it will prompt for confirmation: ``` 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"): ``` If I run powershell in non-interactive mode, I get an error instead: ``` 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 ``` I know that I can use `-Recurse` to have `Remove-Item` proceed as if I had chosen the "Yes" option. Can I somehow proceed as if I had chosen the "No" option? (Just for clarity: `-Force` and `-Confirm:$false` are not what I want here.)