How to Request Confirmations

This example shows how to call the ShouldProcess and ShouldContinue methods to request confirmations from the user before an action is taken.

Important Note:
For more information about how Windows PowerShell handles these requests, see Requesting Confirmation from Cmdlets.

To request confirmation

  1. Ensure that the SupportsShouldProcess parameter of the Cmdlet attribute is set to true. (For functions this is a parameter of the CmdletBinding attribute.)

    [Cmdlet(VerbsDiagnostic.Test, "RequestConfirmationTemplate1",
            SupportsShouldProcess = true)]
    
    
  2. Add a Force parameter to your cmdlet so that the user can override a confirmation request.

    [Parameter()]
    public SwitchParameter Force
    {
      get { return force; }
      set { force = value; }
    }
    private bool force;
    
    
  3. Add an if statement that uses the return value of the ShouldProcess method to determine if the ShouldContinue method is called.

  4. Add a second if statement that uses the return value of the ShouldContinue method and the value of the Force parameter to determine whether the operation should be performed.

Example

In the following code example, the ShouldProcess and ShouldContinue methods are called from within the override of the ProcessRecord method. However, you can also call these methods from the other input processing methods.

protected override void ProcessRecord()
{
  if (ShouldProcess("ShouldProcess target"))
  {
    if (Force || ShouldContinue("", ""))
    {
      // Add code that performs the operation.
    }
  }
}

See Also



Show:
© 2014 Microsoft