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.)
You can use test-path to determine if the directory is empty before you try to delete it:
if (-not (Test-Path .\Test\*.*))
{ Try
{ Remove-Item .\Test -ErrorAction Stop }
Catch { Continue }
}
The Try Catch will handle any errors
This worked for me. The files do not get removed and the script proceeds on. You still see the error about NonInteractive mode, but the command moves on as if No was answered.
remove-item c:\test\test
Write-host "Files are still there, script still going"
If you just want to suppress that error message wrap it in a Try\Catch
Try
{
remove-item c:\test\test
}
Catch
{
}
Write-host "Files are still there, script still going"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With