GetProcessSample03 示例

此示例演示如何实现一个 cmdlet,用于检索本地计算机上的进程。 它提供一个参数,该参数可以接受管道中的对象,或者接受其属性名称与参数名称相同的对象 Name 属性中的值。 此 cmdlet 是 Windows PowerShell Get-Process 2.0 提供的 cmdlet 的简化版本。

如何使用示例生成Visual Studio。

  1. 安装 Windows PowerShell 2.0 SDK 后,导航到 GetProcessSample03 文件夹。 默认位置为 C:\Program Files (x86) \Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\GetProcessSample03。

  2. 双击解决方案 (.sln) 图标。 这会在 Visual Studio 中打开示例项目。

  3. 在“生成”菜单中选择“生成解决方案” 。

    示例的库将构建在默认的 \bin 或 \bin\debug 文件夹中。

如何运行示例

  1. 创建以下模块文件夹:

    [user]/documents/windowspowershell/modules/GetProcessSample03

  2. 将示例程序集复制到 module 文件夹。

  3. 启动 Windows PowerShell。

  4. 运行以下命令,将程序集加载到Windows PowerShell:

    Import-module getprossessample03

  5. 运行以下命令以运行 cmdlet:

    get-proc

要求

此示例需要 Windows PowerShell 2.0。

演示

此示例演示了以下内容。

  • 使用 Cmdlet 属性声明 cmdlet 类。

  • 使用 Parameter 属性声明 cmdlet 参数。

  • 指定参数的位置。

  • 指定 参数从管道接受输入。 输入可以从对象或值取自属性名称与参数名称相同的对象的属性。

  • 声明参数输入的验证属性。

示例

此示例演示了 Get-Proc cmdlet 的实现,该 cmdlet 包含 Name 接受来自管道的输入的参数。

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 retrieved by the cmdlet.
    /// </summary>
    private string[] processNames;

    /// <summary>
    /// Gets or sets the names of the
    /// process that the cmdlet will retrieve.
    /// </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);
        }
      } // End if (processNames ...)
    } // End ProcessRecord.

    #endregion Overrides
  } // End GetProcCommand.
  #endregion GetProcCommand
}

另请参阅

编写 Windows PowerShell Cmdlet