以下代码演示可接受管道输入的 Get-Process
cmdlet 的实现。 此实现定义一个 Name
参数,该参数接受管道输入,根据提供的名称从本地计算机检索进程信息,然后使用 WriteObject(System.Object,System.Boolean) 方法作为将对象发送到管道的输出机制。
注释
可以使用适用于 Windows Vista 和 .NET Framework 3.0 运行时组件的 Microsoft Windows 软件开发工具包下载此 Get-Proc cmdlet 的 C# 源文件(getprov03.cs)。 有关下载说明,请参阅 如何安装 Windows PowerShell 并下载 Windows PowerShell SDK。 <PowerShell 示例> 目录中提供了下载的源文件。
代码示例
namespace Microsoft.Samples.PowerShell.Commands
{
using System;
using System.Diagnostics;
using System.Management.Automation; // Windows PowerShell namespace.
#region GetProcCommand
/// <summary>
/// This class implements the get-proc cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Proc")]
public class GetProcCommand : Cmdlet
{
#region Parameters
/// <summary>
/// The names of the processes to act on.
/// </summary>
private string[] processNames;
/// <summary>
/// Gets or setsthe list of process names on
/// which the Get-Proc cmdlet will work.
/// </summary>
[Parameter(
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string[] Name
{
get { return this.processNames; }
set { this.processNames = value; }
}
#endregion Parameters
#region Cmdlet Overrides
/// <summary>
/// The ProcessRecord method calls the Process.GetProcesses
/// method to retrieve the processes specified by the Name
/// parameter. Then, the WriteObject method writes the
/// associated processes to the pipeline.
/// </summary>
protected override void ProcessRecord()
{
// If no process names are passed to the cmdlet, get all
// processes.
if (this.processNames == null)
{
WriteObject(Process.GetProcesses(), true);
}
else
{
// If process names are passed to the cmdlet, get and write
// the associated processes.
foreach (string name in this.processNames)
{
WriteObject(Process.GetProcessesByName(name), true);
}
} // if (processNames ...
} // ProcessRecord
#endregion Overrides
} // End GetProcCommand class.
#endregion GetProcCommand
}