如何要求確認

這個範例會示範如何呼叫 ShouldProcessShouldContinue 方法,在採取動作之前,要求使用者提出確認的方法,並在採取動作之前要求使用者確認。

重要

如需 Windows PowerShell 如何處理這些要求的詳細資訊,請參閱要求確認

要求確認

  1. 確定 SupportsShouldProcess Cmdlet 屬性的參數設定為 true 。 函數的 (這是 CmdletBinding 屬性的參數。 )

    [Cmdlet(VerbsDiagnostic.Test, "RequestConfirmationTemplate1",
            SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)]
    

    注意

    SupportsShouldProcess單獨使用不保證會提示使用者進行確認。 提示是由的值 $ConfirmPreference 和動作的影響來決定。 使用 ConfirmImpact 設定作業影響的嚴重性。

  2. Force 參數新增至 Cmdlet,讓使用者可以覆寫確認要求。

    [Parameter()]
    public SwitchParameter Force
    {
      get { return force; }
      set { force = value; }
    }
    private bool force;
    
  3. 加入 if 使用ShouldProcess方法之傳回值的語句,以判斷是否已呼叫 ShouldContinue 方法,以判斷是否已呼叫方法。

  4. 新增第二個 if 語句,此語句會使用 ShouldContinue 方法的傳回值和參數的值, Force 以判斷是否應執行作業。

範例

在下列程式碼範例中, ShouldProcessShouldContinue 方法是從 ProcessRecord 方法的覆寫中呼叫的方法所呼叫的程式碼中的程式碼範例。 不過,您也可以從其他輸入處理方法呼叫這些方法。

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

另請參閱

撰寫 Windows PowerShell Cmdlet