技术开发 频道

PowerShell的CmdLet开发的HelloWorld

    【IT168 技术文档】安装完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才能调用,所以好像不太好调试,其实可以用附加到进程的方式来调试.

0
相关文章