添加用于处理命令行输入的参数

cmdlet 的一个输入源是命令行。 本主题介绍如何将参数添加到 Get-Proc cmdlet(如 创建第一个 Cmdlet中所述),以便 cmdlet 可以根据传递给 cmdlet 的显式对象处理本地计算机的输入。 此处所述的 Get-Proc cmdlet 会根据其名称检索进程,然后在命令提示符处显示有关进程的信息。

定义 Cmdlet 类

cmdlet 创建的第一步是 cmdlet 命名和实现 cmdlet 的 .NET Framework 类的声明。 此 cmdlet 检索进程信息,因此此处选择的谓词名称为“Get”。(几乎任何能够检索信息的 cmdlet 都可以处理命令行输入。有关批准的 cmdlet 谓词的详细信息,请参阅 Cmdlet 谓词名称

下面是 Get-Proc cmdlet 的类声明。 有关此定义的详细信息,请参阅 创建第一个 Cmdlet

[Cmdlet(VerbsCommon.Get, "proc")]
public class GetProcCommand: Cmdlet
<Cmdlet(VerbsCommon.Get, "Proc")> _
Public Class GetProcCommand
    Inherits Cmdlet

声明参数

cmdlet 参数使用户能够向 cmdlet 提供输入。 在以下示例中,Get-ProcGet-Member 是管道 cmdlet 的名称,MemberTypeGet-Member cmdlet 的参数。 该参数具有参数“property”。

PS> Get-Proc;Get-Member -MemberType 属性

若要声明 cmdlet 的参数,必须先定义表示参数的属性。 在 Get-Proc cmdlet 中,唯一的参数是 Name,在本例中表示要检索的 .NET Framework 进程对象的名称。 因此,cmdlet 类定义字符串类型的属性以接受名称数组。

下面是 Get-Proc cmdlet Name 参数的参数声明。

/// <summary>
/// Specify the cmdlet Name parameter.
/// </summary>
  [Parameter(Position = 0)]
  [ValidateNotNullOrEmpty]
  public string[] Name
  {
    get { return processNames; }
    set { processNames = value; }
  }
  private string[] processNames;

  #endregion Parameters
<Parameter(Position:=0), ValidateNotNullOrEmpty()> _
Public Property Name() As String()
    Get
        Return processNames
    End Get

    Set(ByVal value As String())
        processNames = value
    End Set

End Property

若要通知 Windows PowerShell 运行时此属性是 Name 参数,System.Management.Automation.ParameterAttribute 属性添加到属性定义中。 声明此属性的基本语法是 [Parameter()]

注释

参数必须显式标记为公共。 未标记为内部公共默认值且未由 Windows PowerShell 运行时找到的参数。

此 cmdlet 对 Name 参数使用字符串数组。 如果可能,cmdlet 还应将参数定义为数组,因为这允许 cmdlet 接受多个项。

关于参数定义的注意事项

  • 应尽可能重复使用预定义的 Windows PowerShell 参数名称和数据类型,以确保 cmdlet 与 Windows PowerShell cmdlet 兼容。 例如,如果所有 cmdlet 都使用预定义的 Id 参数名称来标识资源,则无论它们使用什么 cmdlet,用户都可以轻松理解参数的含义。 基本上,参数名称遵循与公共语言运行时(CLR)中用于变量名称的规则相同。 有关参数命名的详细信息,请参阅 Cmdlet 参数名称

  • Windows PowerShell 保留几个参数名称,以提供一致的用户体验。 请勿使用这些参数名称:WhatIfConfirmVerboseDebugWarnErrorActionErrorVariableOutVariableOutBuffer。 此外,保留这些参数名称的以下别名:vbdbeaevovob

  • Name 是一个简单的通用参数名称,建议在 cmdlet 中使用。 最好选择类似于这样的参数名称,而不是对特定 cmdlet 唯一且难以记住的复杂名称。

  • 参数在 Windows PowerShell 中不区分大小写,但默认情况下 shell 会保留大小写。 参数的区分大小写取决于 cmdlet 的作。 参数将传递给命令行中指定的参数。

  • 有关其他参数声明的示例,请参阅 Cmdlet 参数

将参数声明为位置或命名参数

cmdlet 必须将每个参数设置为位置参数或命名参数。 这两种类型的参数都接受单个参数、用逗号分隔的多个参数和布尔设置。 布尔参数(也称为 开关)仅处理布尔设置。 该开关用于确定参数的存在。 建议的默认值为 false

示例 Get-Proc cmdlet 将 Name 参数定义为位置参数,位置为 0。这意味着,将为此参数自动插入用户在命令行上输入的第一个参数。 如果要定义一个命名参数,用户必须从命令行中指定参数名称,请将 Position 关键字保留在属性声明外。

注释

除非必须命名参数,否则我们建议你设置最常用的参数位置,以便用户不必键入参数名称。

将参数声明为必需参数或可选参数

cmdlet 必须将每个参数设置为可选参数或必需参数。 在示例 Get-Proc cmdlet 中,Name 参数定义为可选参数,因为 Mandatory 关键字未在属性声明中设置。

支持参数验证

示例 Get-Proc cmdlet 将输入验证属性(System.Management.Automation.ValidateNotNullOrEmptyAttribute)添加到 Name 参数,以启用输入既不是 null 也不是空的验证。 此属性是 Windows PowerShell 提供的多个验证属性之一。 有关其他验证属性的示例,请参阅 验证参数输入

[Parameter(Position = 0)]
[ValidateNotNullOrEmpty]
public string[] Name

重写输入处理方法

如果 cmdlet 要处理命令行输入,则必须重写相应的输入处理方法。 创建第一个 Cmdlet中引入了基本输入处理方法。

Get-Proc cmdlet 重写 System.Management.Automation.Cmdlet.ProcessRecord 方法来处理用户或脚本提供的 Name 参数输入。 此方法获取每个请求的进程名称的进程;如果没有提供名称,则获取所有进程的进程。 请注意,在 System.Management.Automation.Cmdlet.ProcessRecord中,调用 System.Management.Automation.Cmdlet.WriteObject 是用于将输出对象发送到管道的输出机制。 此调用的第二个参数 enumerateCollection设置为 true,以通知 Windows PowerShell 运行时枚举进程对象的输出数组,并将一个进程一次写入命令行。

protected override void ProcessRecord()
{
  // If no process names are passed to the cmdlet, get all processes.
  if (processNames == null)
  {
    // Write the processes to the pipeline making them available
    // to the next cmdlet. The second argument of this call tells
    // PowerShell to enumerate the array, and send one process at a
    // time to the pipeline.
    WriteObject(Process.GetProcesses(), true);
  }
  else
  {
    // If process names are passed to the cmdlet, get and write
    // the associated processes.
    foreach (string name in processNames)
    {
      WriteObject(Process.GetProcessesByName(name), true);
    }
  }
}
Protected Overrides Sub ProcessRecord()

    '/ If no process names are passed to the cmdlet, get all processes.
    If processNames Is Nothing Then
        Dim processes As Process()
        processes = Process.GetProcesses()
    End If

    '/ If process names are specified, write the processes to the
    '/ pipeline to display them or make them available to the next cmdlet.

    For Each name As String In processNames
        '/ The second parameter of this call tells PowerShell to enumerate the
        '/ array, and send one process at a time to the pipeline.
        WriteObject(Process.GetProcessesByName(name), True)
    Next

End Sub 'ProcessRecord

代码示例

有关完整的 C# 示例代码,请参阅 GetProcessSample02 示例

定义对象类型和格式

Windows PowerShell 使用 .NET Framework 对象在 cmdlet 之间传递信息。 因此,cmdlet 可能需要定义自己的类型,或者 cmdlet 可能需要扩展另一个 cmdlet 提供的现有类型。 有关定义新类型或扩展现有类型的详细信息,请参阅 扩展对象类型和格式

生成 Cmdlet

实现 cmdlet 后,必须使用 Windows PowerShell 管理单元将其注册到 Windows PowerShell。 有关注册 cmdlet 的详细信息,请参阅 如何注册 Cmdlet、提供程序和主机应用程序

测试 Cmdlet

将 cmdlet 注册到 Windows PowerShell 时,可以通过在命令行上运行它来测试它。 下面是测试示例 cmdlet 的代码的两种方法。 有关从命令行使用 cmdlet 的详细信息,请参阅 windows PowerShell 入门

  • 在 Windows PowerShell 提示符下,使用以下命令列出名为“IEXPLORE”的 Internet Explorer 进程。

    Get-Proc -Name iexplore
    

    将显示以下输出。

    Handles  NPM(K)  PM(K)   WS(K)  VS(M)  CPU(s)   Id   ProcessName
    -------  ------  -----   -----  -----   ------ --   -----------
        354      11  10036   18992    85   0.67   3284   iexplore
    
  • 若要列出名为“IEXPLORE”、“OUTLOOK”和“NOTEPAD”的 Internet Explorer、Outlook 和记事本进程,请使用以下命令。 如果有多个进程,则显示所有这些进程。

    Get-Proc -Name iexplore, outlook, notepad
    

    将显示以下输出。

    Handles  NPM(K)  PM(K)   WS(K)  VS(M)  CPU(s)   Id   ProcessName
    -------  ------  -----   -----  -----  ------   --   -----------
        732      21  24696    5000    138   2.25  2288   iexplore
        715      19  20556   14116    136   1.78  3860   iexplore
       3917      62  74096   58112    468 191.56  1848   OUTLOOK
         39       2   1024    3280     30   0.09  1444   notepad
         39       2   1024     356     30   0.08  3396   notepad
    

另请参阅

添加处理管道输入 的参数

创建第一个 Cmdlet

扩展对象类型和格式设置

如何注册 Cmdlet、提供程序和主机应用程序

Windows PowerShell 参考

Cmdlet 示例