此示例演示如何调用 System.Management.Automation.Cmdlet.ShouldProcess 和 System.Management.Automation.Cmdlet.ShouldContinue 方法,以在操作之前请求用户确认。
重要
有关请求如何处理Windows PowerShell,请参阅请求确认。
请求确认
- 确保 - SupportsShouldProcessCmdlet 属性的 参数设置为- true。 (对于函数,这是 CmdletBinding attribute.)- [Cmdlet(VerbsDiagnostic.Test, "RequestConfirmationTemplate1", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)]- 备注 - SupportsShouldProcess单独使用 并不保证系统提示用户进行确认。 提示由 的值和操作- $ConfirmPreference的影响决定。 使用- ConfirmImpact设置操作影响的严重性。
- 将 - Force参数添加到 cmdlet,以便用户可以替代确认请求。- [Parameter()] public SwitchParameter Force { get { return force; } set { force = value; } } private bool force;
- 添加一个语句,该语句使用 - ifSystem.Management.Automation.Cmdlet.ShouldProcess 方法的返回值来确定是否调用 System.Management.Automation.Cmdlet.ShouldContinue 方法。
- 添加第二个语句,该语句使用 - ifSystem.Management.Automation.Cmdlet.ShouldContinue 方法的返回值和 参数的值来确定- Force是否应该执行该操作。
示例
在下面的代码示例中,从System.Management.Automation.Cmdlet.ProcessRecord方法的重写中调用System.Management.Automation.Cmdlet.ShouldProcess和System.Management.Automation.Cmdlet.ShouldContinue方法。 但是,也可以从其他输入处理方法调用这些方法。
protected override void ProcessRecord()
{
  if (ShouldProcess("ShouldProcess target"))
  {
    if (Force || ShouldContinue("", ""))
    {
      // Add code that performs the operation.
    }
  }
}