Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automatically choose "No" when Remove-Item prompts for confirmation?

Tags:

powershell

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.)

like image 675
Fabian Schmied Avatar asked Nov 27 '13 13:11

Fabian Schmied


Video Answer


3 Answers

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

like image 78
mjolinor Avatar answered Oct 18 '22 00:10

mjolinor


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"
like image 34
malexander Avatar answered Oct 18 '22 00:10

malexander


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
like image 1
Jim Avatar answered Oct 17 '22 23:10

Jim