Cmdlet 輸入處理方法

Cmdlet 必須覆寫此主題中所述的一或多個輸入處理方法,才能執行其工作。 這些方法可讓 Cmdlet 執行前置處理、輸入處理和後置處理的作業。 這些方法也可讓您停止 Cmdlet 處理。 如需如何使用這些方法的更詳細範例,請參閱 SelectStr 教學課程。

前置處理作業

Cmdlet 應覆寫 BeginProcessing 方法,以新增任何對稍後將由 Cmdlet 處理之記錄有效的前置處理作業。 當 PowerShell 處理命令管線時,PowerShell 會針對管線中的每個 Cmdlet 實例呼叫這個方法一次。 如需 PowerShell 如何叫用命令管線的詳細資訊,請參閱 Cmdlet 處理生命週期

下列程式碼顯示 BeginProcessing 方法的執行。

protected override void BeginProcessing()
{
  // Replace the WriteObject method with the logic required by your cmdlet.
  WriteObject("This is a test of the BeginProcessing template.");
}

輸入處理作業

指令程式可以覆寫 ProcessRecord 方法,以處理傳送至 Cmdlet 的輸入。 當 PowerShell 處理命令管線時,PowerShell 會針對 Cmdlet 所處理的每個輸入記錄,呼叫這個方法。 如需 PowerShell 如何叫用命令管線的詳細資訊,請參閱 Cmdlet 處理生命週期

下列程式碼顯示 ProcessRecord 方法的執行。

protected override void ProcessRecord()
{
  // Replace the WriteObject method with the logic required by your cmdlet.
  WriteObject("This is a test of the ProcessRecord template.");
}

後續處理作業

Cmdlet 應覆寫 system.string 方法, 以新增對 Cmdlet 所處理之所有記錄有效的任何後置處理作業。 例如,您的 Cmdlet 可能必須在完成處理之後清除物件變數。

當 PowerShell 處理命令管線時,PowerShell 會針對管線中的每個 Cmdlet 實例呼叫這個方法一次。 不過,請務必記住,如果 Cmdlet 在其輸入處理過程中中途取消,或 Cmdlet 的任何部分中發生終止錯誤,則 PowerShell 執行時間不會呼叫 EndProcessing 方法。 基於這個理由,需要物件清理的 Cmdlet 應該會執行完整的 IDisposable 模式,包括完成項,如此執行時間就可以在處理結束時呼叫 EndProcessing 和 IDisposable 方法。 如需 PowerShell 如何叫用命令管線的詳細資訊,請參閱 Cmdlet 處理生命週期

下列程式碼顯示 EndProcessing 方法的執行。

protected override void EndProcessing()
{
  // Replace the WriteObject method with the logic required by your cmdlet.
  WriteObject("This is a test of the EndProcessing template.");
}

另請參閱

System.Management.Automation.Cmdlet.BeginProcessing

System.Management.Automation.Cmdlet.ProcessRecord

管理. Cmdlet. EndProcessing

SelectStr 教學課程

System.IDisposable

Windows PowerShell 殼層 SDK