当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何从 Cmdlet 内调用 Cmdlet

作者:精品下载站 日期:2024-12-14 02:49:56 浏览:14 分类:玩电脑

如何从 Cmdlet 内调用 Cmdlet


此示例演示如何直接从另一个二进制 cmdlet 中调用派生自 [System.Management.Automation.Cmdlet] 的二进制 cmdlet,这允许您将调用的 cmdlet 的功能添加到二进制 cmdlet你正在发展。在此示例中,调用 Get-Process cmdlet 来获取本地计算机上运行的进程。对 Get-Process cmdlet 的调用相当于以下命令。此命令检索名称以字符“a”到“t”开头的所有进程。

Get-Process -name [a-t]*

这很重要

您只能调用那些直接从 System.Management.Automation.Cmdlet 类派生的 cmdlet。您无法调用派生自 System.Management.Automation.PSCmdlet 类的 cmdlet。有关示例,请参阅如何从 PSCmdlet 内调用 PSCmdlet。

从 cmdlet 内调用 cmdlet

  1. 确保引用定义要调用的 cmdlet 的程序集,并添加适当的 using 语句。在此示例中,添加了以下命名空间。

    using System.Diagnostics;
    using System.Management.Automation;   // PowerShell assembly.
    using Microsoft.PowerShell.Commands;  // PowerShell cmdlets assembly you want to call.
    
  2. 在 cmdlet 的输入处理方法中,创建要调用的 cmdlet 的新实例。在此示例中,将创建 Microsoft.PowerShell.Commands.GetProcessCommand 类型的对象以及包含调用 cmdlet 时使用的参数的字符串。

    GetProcessCommand gp = new GetProcessCommand();
    gp.Name = new string[] { "[a-t]*" };
    
  3. 调用 System.Management.Automation.Cmdlet.Invoke* 方法来调用 Get-Process cmdlet。

      foreach (Process p in gp.Invoke<Process>())
      {
        Console.WriteLine(p.ToString());
      }
    }
    

例子

在此示例中,从 cmdlet 的 System.Management.Automation.Cmdlet.BeginProcessing 方法中调用 Get-Process cmdlet。

using System;
using System.Diagnostics;
using System.Management.Automation;   // PowerShell assembly.
using Microsoft.PowerShell.Commands;  // PowerShell cmdlets assembly you want to call.

namespace SendGreeting
{
  // Declare the class as a cmdlet and specify an
  // appropriate verb and noun for the cmdlet name.
  [Cmdlet(VerbsCommunications.Send, "GreetingInvoke")]
  public class SendGreetingInvokeCommand : Cmdlet
  {
    // Declare the parameters for the cmdlet.
    [Parameter(Mandatory = true)]
    public string Name { get; set; }

    // Override the BeginProcessing method to invoke
    // the Get-Process cmdlet.
    protected override void BeginProcessing()
    {
      GetProcessCommand gp = new GetProcessCommand();
      gp.Name = new string[] { "[a-t]*" };
      foreach (Process p in gp.Invoke<Process>())
      {
        WriteVerbose(p.ToString());
      }
    }

    // Override the ProcessRecord method to process
    // the supplied user name and write out a
    // greeting to the user by calling the WriteObject
    // method.
    protected override void ProcessRecord()
    {
      WriteObject("Hello " + Name + "!");
    }
  }
}

参见

编写 Windows PowerShell Cmdlet

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯