Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

How to Request Confirmations

 

This example shows how to call the Overload:System.Management.Automation.Cmdlet.ShouldProcess and Overload:System.Management.Automation.Cmdlet.ShouldContinue methods to request confirmations from the user before an action is taken.

System_CAPS_importantImportant

For more information about how Windows PowerShell handles these requests, see Requesting Confirmation.

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 Overload:System.Management.Automation.Cmdlet.ShouldProcess method to determine if the Overload:System.Management.Automation.Cmdlet.ShouldContinue method is called.

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

Example

In the following code example, the M:System.Management.Automation.Cmdlet.ShouldProcess(string) and M:System.Management.Automation.Cmdlet.ShouldContinue(string,string) 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.
    }
  }
}

Show: