GetProcessSample02 示例
此示例演示如何编写一个 cmdlet 来检索本地计算机上的进程。 它提供一个 Name
参数,可用于指定要检索的进程。 此 cmdlet 是 Windows PowerShell 2.0 提供的 Get-Process
cmdlet 的简化版本。
如何使用 Visual Studio 生成示例
安装 Windows PowerShell 2.0 SDK 后,导航到 GetProcessSample02 文件夹。 默认位置为
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\GetProcessSample02
。双击解决方案(.sln)文件的图标。 这将在 Visual Studio 中打开示例项目。
在 生成 菜单中,选择 “生成解决方案”,以在默认
\bin
或\bin\debug
文件夹中为示例生成库。
如何运行示例
创建以下模块文件夹:
[user]\Documents\WindowsPowerShell\Modules\GetProcessSample02
将示例程序集复制到模块文件夹。
启动 Windows PowerShell。
运行以下命令将程序集加载到 Windows PowerShell 中:
Import-Module getprossessample02
运行以下命令以运行 cmdlet:
Get-Proc
要求
此示例需要 Windows PowerShell 2.0。
演示
此示例演示了以下内容。
使用 Cmdlet 属性声明 cmdlet 类。
使用 Parameter 属性声明 cmdlet 参数。
指定参数的位置。
声明参数输入的验证属性。
示例
此示例演示包含 Name
参数的 Get-Proc cmdlet 的实现。
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 list of process names on which
/// the Get-Proc cmdlet will work.
/// </summary>
[Parameter(Position = 0)]
[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 process objects 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 cmdlet, get and write
// the associated processes.
foreach (string name in this.processNames)
{
WriteObject(Process.GetProcessesByName(name), true);
}
} // End if (processNames...).
} // End ProcessRecord.
#endregion Cmdlet Overrides
} // End GetProcCommand class.
#endregion GetProcCommand
}