Question:
When using PowerShell’s Remove-Item
to remove a directory that is not empty, it will prompt for confirmation:
1 2 3 4 5 6 7 |
PS C:\Users\ Confirm The item at C:\Users\ 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:
1 2 3 4 5 6 7 |
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.)
Answer:
IMHO the correct answer is to set the -ErrorAction to SilentlyContinue. Then you don’t have to have empty try-catch code.
Like this:
1 2 |
PS C:\Users\ |