Powershell Cmdlet.ShouldProcess Method default answer

1.2k views Asked by At

I have a powershell script in which I have implemented the should process method with a high ConfirmImpact to ensure a prompt occurs.

Prompting is working as expected however the default response when nothing is entered is "Y"

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

Is there a way to change the default response to "N"? I would like the user to have to explicitly enter Y if they want to apply the script. I've written a pretty heavy handed script and last thing I want is for the script user to just hit enter without verifying what they are applying it to.

I've read the documentation on it and there is no mention of this anywhere.

2

There are 2 answers

0
Jessie On BEST ANSWER

After further research I have found a way to do this. In order to have a default response set to NO, ShouldContinue Method should be used instead of ShouldProcess.

Reading the documentation for ShouldContinue has a section in the format

ShouldContinue(String, String, Boolean, Boolean, Boolean)

The first boolean is to reference a security impact. True if the operation being confirmed has a security impact. If specified, the default option selected in the selection menu is 'No'.

6
Mathias R. Jessen On

No, unfortunately not

With the current implementation of ShouldProcess(), the default option is always the first choice


Whether or not ShouldProcess() prompts the user to confirm the operation depends on whether the $ConfirmPreference automatic variable has a value higher than the ConfirmImpact attribute of the cmdlet being called.

$ConfirmPreference defaults to High, the highest severity impact level available.

To always void confirmation prompts for ShouldProcess(), set $ConfirmPreference to None:

# Define a function with ConfirmImpact Medium or higher
function f {
  [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
  param()

  if($PSCmdlet.ShouldProcess("Dangerous operation")) {
    Write-Host 'Welcome to the Danger Zone' -ForegroundColor Red
  }
}

# Set $ConfirmPreference to `Medium` to prompt for confirmation
$ConfirmPreference = 'Medium'

# Call our function - you'll be prompted for confirmation
f

# Set $ConfirmPreference to `None` to suppress confirmation prompts
$ConfirmPreference = 'None'

# Call our function - you won't be prompted for confirmation
f