How to automatically select "No" for "Delete-Item" requests for confirmation?

When using PowerShell Remove-Item to remove a directory that is not empty, it asks 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 so that the Remove-Item continues as if I selected the Yes option. Can I somehow act as if I chose the No option?

(Just for clarity: -Force and -Confirm:$false not what I want here.)

+7
powershell
source share
2 answers

It worked for me. Files are not deleted, but the script continues. You still see the error in NonInteractive mode, but the command moves as if No were answered.

 remove-item c:\test\test Write-host "Files are still there, script still going" 

If you just want this error message to wrap it in Try \ Catch

 Try { remove-item c:\test\test } Catch { } Write-host "Files are still there, script still going" 
+1
source share

You can use the test path to determine if the directory is empty before it is deleted:

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

Try Catch will handle any errors

+2
source share

All Articles