PowerShell的CmdLet開發的HelloWorld
安 裝完windows Vista SDK後,終於可以開始CmdLet的開發了.如果安裝了Samples的同學,可以直接去看示例:X:/Program Files/Microsoft SDKs/Windows/v6.0/Samples/SysMgmt/WindowsPowerShell 其中X是PS所在的安裝盤.下面讓偶手把手地說一下該怎麼建立一個CmdLet吧:
1.打開VS2005,創建一個windows的運行庫.
2.添加引用:C:/Program Files/Reference Assemblies/Microsoft/WindowsPowerShell/v1.0/System.Management.Automation.dll
3.新建一個類文件,同時
using System.Management.Automation;
using System.ComponentModel;(這個在安裝時會用到)
4.下面開始寫代碼了:
//先來完成cmdlet的實體類[Cmdlet(VerbsCommon.Get, "HelloWorld")] //大膽地猜測一下,PS在加載cmdlet程序集的時候,是用反射的方式來識別的,反射的時候就是靠這個attribute來實現,這裏面有兩個參數,第一個是動作,後一個是名字.這是cmdlet的命名方式:動詞+名詞
public class ExecuteShell : Cmdlet // 繼承自cmdlet的基類
{
private string argus;
[Parameter(Position = 0)] //大家可以發現很有意思在這裏面,隨處都可以看到attribute,這裏指寫了第一個參數,直接就反射到類對應的屬性上了.
[ValidateNotNullOrEmpty]
public string Args
{
get { return argus; }
set { argus = value; }
}
protected override void ProcessRecord()
//處理請求,我們我這裏只是簡單地輸出一下信息.
{
if (argus != null && argus.Length > 0)
{
WriteCommandDetail("Hello World:" + argus);
}
}
}
//再來看看cmdlet的安裝類
[RunInstaller(true)] //又是這種attribute
public class HelloWordSnapIn: PSSnapIn
{
/// <summary>
/// Create an instance of the GetProcPSSnapIn01
/// </summary>
public PSclient()
: base()
{
}
/// <summary>
/// Get a name for this PowerShell snap-in. This name will be used in registering
/// this PowerShell snap-in.
/// 注意這裏面的名字最爲重要在下面將要講到
/// </summary>
public override string Name
{
get
{
return "HelloWordSnapIn";
}
}
/// <summary>
/// Vendor information for this PowerShell snap-in.
/// </summary>
public override string Vendor
{
get
{
return "BrainIron";
}
}
/// <summary>
/// Gets resource information for vendor. This is a string of format:
/// resourceBaseName,resourceName.
/// </summary>
public override string VendorResource
{
get
{
return "HelloWordSnapIn,BrainIron";
}
}
/// <summary>
/// Description of this PowerShell snap-in.
/// </summary>
public override string Description
{
get
{
return "This is a PowerShell snap-in that includes the Get-HelloWorld cmdlet. this is a demo, design by Brian";
}
}
}
編譯生成:HelloWorldCmdLet.dll
6.這時候該安裝了:使用Installutil.exe HelloWorldCmdLet.dll來把安裝它.Installutil.exe如果你找不到,那麼應該在SDK的BIN目錄裏面肯定可以找得到.
7.這時候打開PS,使用Get-HelloWorld 命令會發現提示不支持這個命令.這時候要用:Add-PSSnapin HelloWordSnapIn 來把它註冊到PS的控制檯中,這個命令的後面的那個名字就是我上面說的重要的名字,而不是類名.然後再用Get-HelloWorld 命令就可以看到成果了.
8.調試.因爲程序要先註冊到PS中,PS才能調用,所以好像不太好調試,其實可以用附加到進程的方式來調試.