托管PowerShell无法在同一个程序集中看到Cmdlet

Ida*_*rye 9 c# powershell cmdlet

我正在尝试从我的C#代码运行PowerShell脚本,它将使用运行它们的程序集中的自定义Cmdlet.这是代码:

using System;
using System.Management.Automation;

[Cmdlet(VerbsCommon.Get,"Hello")]
public class GetHelloCommand:Cmdlet
{
    protected override void EndProcessing()
    {
        WriteObject("Hello",true);
    }
}

class MainClass
{
    public static void Main(string[] args)
    {
        PowerShell powerShell=PowerShell.Create();
        powerShell.AddCommand("Get-Hello");
        foreach(string str in powerShell.AddCommand("Out-String").Invoke<string>())
            Console.WriteLine(str);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我得到一个CommandNotFoundException.我写错了Cmdlet吗?有什么我需要做的事情来在PowerShell或Runspace中注册我的Cmdlet吗?

x0n*_*x0n 9

使用当前代码段执行此操作的最简单方法如下:

using System; 
using System.Management.Automation; 

[Cmdlet(VerbsCommon.Get,"Hello")] 
public class GetHelloCommand:Cmdlet 
{ 
    protected override void EndProcessing() 
    { 
        WriteObject("Hello",true); 
    } 
} 

class MainClass 
{ 
    public static void Main(string[] args) 
    { 
        PowerShell powerShell=PowerShell.Create();

        // import commands from the current executing assembly
        powershell.AddCommand("Import-Module")
            .AddParameter("Assembly",
                  System.Reflection.Assembly.GetExecutingAssembly())
        powershell.Invoke()
        powershell.Commands.Clear()

        powershell.AddCommand("Get-Hello"); 
        foreach(string str in powerShell.AddCommand("Out-String").Invoke<string>()) 
            Console.WriteLine(str); 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

这假设是PowerShell v2.0(您可以使用$ psversiontable或版权日期检查您的控制台,应该是2009年.)如果您使用的是win7,那么您将使用v2.


Rom*_*min 5

另一种简单的方法是在运行空间配置中注册cmdlet,使用此配置创建运行空间,然后使用该运行空间。

using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

[Cmdlet(VerbsCommon.Get, "Hello")]
public class GetHelloCommand : Cmdlet
{
    protected override void EndProcessing()
    {
        WriteObject("Hello", true);
    }
}

class MainClass
{
    public static void Main(string[] args)
    {
        PowerShell powerShell = PowerShell.Create();
        var configuration = RunspaceConfiguration.Create();
        configuration.Cmdlets.Append(new CmdletConfigurationEntry[] { new CmdletConfigurationEntry("Get-Hello", typeof(GetHelloCommand), "") });
        powerShell.Runspace = RunspaceFactory.CreateRunspace(configuration);
        powerShell.Runspace.Open();

        powerShell.AddCommand("Get-Hello");
        foreach (string str in powerShell.AddCommand("Out-String").Invoke<string>())
            Console.WriteLine(str);
    }
}
Run Code Online (Sandbox Code Playgroud)

以防万一,使用此方法,不必公开cmdlet类。