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
  {
  ///
  /// Create an instance of the GetProcPSSnapIn01
  ///

  public PSclient()
  : base()
  {
  }
  ///
  /// Get a name for this PowerShell snap-in. This name will be used in registering
  /// this PowerShell snap-in.
  /// 注意这里面的名字最为重要在下面将要讲到
  ///

  public override string Name
  {
  get
  {
  return "HelloWordSnapIn";
  }
  }
  ///
  /// Vendor information for this PowerShell snap-in.
  ///

  public override string Vendor
  {
  get
  {
  return "BrainIron";
  }
  }
  ///
  /// Gets resource information for vendor. This is a string of format:
  /// resourceBaseName,resourceName.
  ///

  public override string VendorResource
  {
  get
  {
  return "HelloWordSnapIn,BrainIron";
  }
  }
  ///
  /// Description of this PowerShell snap-in.
  ///

  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才能调用,所以好像不太好调试,其实可以用附加到进程的方式来调试.

本文转自
http://blog.joycode.com/chinahuman/archive/2007/09/18/108595.aspx
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值