Cmdlet 输入处理方法

Cmdlet 必须重写本主题中所述的一个或多个输入处理方法才能执行它们的工作。 这些方法允许 cmdlet 执行预处理、输入处理和后处理操作。 这些方法还允许停止 cmdlet 处理。 有关如何使用这些方法的更详细示例,请参阅 SelectStr 教程

预处理操作

Cmdlet 应重写 System.Management.Automation.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.");
}

输入处理操作

Cmdlet 可以重写 System.Management.Automation.Cmdlet.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.Management.Automation.Cmdlet.EndProcessing 方法,以添加对 cmdlet 处理的所有记录有效的任何后处理操作。 例如,cmdlet 可能需要在处理完成后清理对象变量。

当 PowerShell 处理命令管道时,PowerShell 会针对管道中 cmdlet 的每个实例调用此方法一次。 但是,必须记住,如果 cmdlet 在其输入处理过程中中途取消,或者 cmdlet 的任何部分发生终止错误,PowerShell 运行时将不会调用 EndProcessing 方法。 因此,需要对象清理的 cmdlet 应实现完整的 System.IDisposable 模式(包括终结器),以便运行时可以在处理结束时同时调用 EndProcessing 和 System.IDisposable.Dispose 方法。 有关 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

System.Management.Automation.Cmdlet.EndProcessing

SelectStr 教程

System.IDisposable

Windows PowerShell Shell SDK