Is there a way to supress any interactive prompts in a PowerShell script?

Solution 1:

The solution proposed by Eris effectively starts another PowerShell instance. An alternative way to do this, with simpler syntax, is to shell out to another instance of powershell.exe.

powershell.exe -NonInteractive -Command "Remove-Item 'D:\Temp\t'"

Solution 2:

See Get-Help about_Preference_Variables:

$ConfirmPreference
------------------
    Determines whether Windows PowerShell automatically prompts you for
    confirmation before running a cmdlet or function.

...

None:    Windows PowerShell does not prompt automatically.
                         To request confirmation of a particular command, use
                         the Confirm parameter of the cmdlet or function.

So:

> $ConfirmPreference = 'None'

Solution 3:

Ok, This is really ugly, but holy mustard stains it "works".

Issues:

  • I have not figured out how to continue after the first error
  • In this case, it removes plain files, then stops at the first folder
  • I have not figured out how to make this cmdlet work if I add the UseTransaction parameter
  • This will only work for the Simple case (commands that don't do a lot of stuff with the current environment). I have not tested anything complex

    $MyPS = [Powershell]::Create()
    $MyPS.Commands.AddCommand("Remove-Item")
    $MyPS.Commands.AddParameter("Path", "D:\Temp\t")
    $MyPS.Invoke()

Output:

Commands                                                                                                                 
--------                                                                                                                 
{Remove-Item}                                                                                                            
{Remove-Item}                                                                                                            
Exception calling "Invoke" with "0" argument(s): "A command that prompts the user failed because the host program or the 
command type does not support user interaction. The host was attempting to request confirmation with the following 
message: The item at D:\Temp\t 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?"
At line:19 char:1
+ $MyPS.Invoke()
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CmdletInvocationException

Solution 4:

I was also having the same issue. The solutions tried by me included:

  • ECHO 'Y' |
  • Command-Name -Force
  • $ConfirmPreference = 'None'

However, none of them seemed to do the trick.

What finally solved the problem was:

Powershell-Cmdlet -Confirm:$false

It suppresses all confirmation prompts for the duration of the command and the command would be processed without any confirmation.