如果想自定义一个类似于PowerShell的Get-Process的cmdlet,例如Get-Proc,如何自己编写这样一个cmdlet呢?查阅msdn,其基本步骤是:
1. 确定cmdlet的名字:通常cmdlet都采取verb-noun的方式,确定自定义的cmdlet属于哪个cmdlet verb,并确定一个具体的名词。本例中,Get-Proc属于Verbs.Common.Get,名词则是"Proc";
2. 确定cmdlet的类名,通常,以verbnoun+"command"后缀作为类名。本例中,GetProcCommand;
3. 实现类:通常,自定义的cmdlet只需继承Cmdlet类,而不是PSCmdlet类,有关二者的介绍,可参考:
http://msdn.microsoft.com/en-us/library/ms714395(v=VS.85).aspx
4. 编写Snap-in类,供注册自定义的cmdlet到PowerShell Session中;
代码示例:
Step 1:打开Visual Studio,创建dll工程"Mycmdletlib”,添加引用:System.Management.Automation和System.Configuration.Install;注System.Management.Automation位于目录"C:/Program Files/Reference Assemblies/Microsoft/WindowsPowerShell/v1.0"下;
Step 2:实现GetProcCommand类和Snap-in类:
using System; using System.Collections.Generic; using System.Text; using System.Management.Automation; using System.Diagnostics; using System.ComponentModel; namespace Mycmdletlib { [Cmdlet(VerbsCommon.Get, "Proc")] public class GetProcCommand : Cmdlet { protected override void ProcessRecord() { Process[] p = Process.GetProcesses(); // Write the processes to the pipeline making them available // to the next cmdlet. The second parameter of this call tells // PowerShell to enumerate the array, and send one process at a // time to the pipeline. WriteObject(p, true); } } [RunInstaller(true)] public class MyLibSnapIn : PSSnapIn { public MyLibSnapIn() : base() { } public override string Name { get { return "MyLibSnapIn"; } } public override string Vendor { get { return "Fei"; } } public override string Description { get { return "About how to write cmdlets"; } } } }
注1:对于GetProcCommand类,通常我们只需要重载ProcessRecord方法,具体可参考:http://msdn.microsoft.com/en-us/library/ms714395(v=VS.85).aspx
Step 3:注册自定义的cmdlet Get-Proc:
打开PowerShell ISE,输入如下命令:
set-alias installutil $env:windir/Microsoft.NET/Framework/v2.0.50727/installutil
set-location 'C:/PSTest/Mycmdletlib/Mycmdletlib/bin/Debug'
installutil Mycmdletlib.dll
Step 4: 检查Snap-in是否注册成功:
PS> get-pssnapin -registered
可以看到如下结果:
Step 5: 把Snap-in加入当前Shell Session
PS> add-pssnapin MyLibSnapIn
Step 6:检查自定义的cmdlet是否成功:
PS> Get-Proc | Format-list