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.
Important |
|---|
For more information about how Windows PowerShell handles these requests, see Requesting Confirmation. |
To request confirmation
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)]
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;
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.
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.
}
}
}
