PowerShell - 如何在Runspace中导入模块

Abs*_*lom 13 c# powershell powershell-2.0


我正在尝试在C#中创建一个cmdlet.代码看起来像这样:

[Cmdlet(VerbsCommon.Get, "HeapSummary")]
public class Get_HeapSummary : Cmdlet
{
    protected override void ProcessRecord()
    {
        RunspaceConfiguration config = RunspaceConfiguration.Create();
        Runspace myRs = RunspaceFactory.CreateRunspace(config);
        myRs.Open();

        RunspaceInvoke scriptInvoker = new RunspaceInvoke(myRs);
        scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

        Pipeline pipeline = myRs.CreatePipeline();
        pipeline.Commands.Add(@"Import-Module G:\PowerShell\PowerDbg.psm1");
        //...
        pipeline.Invoke();

        Collection<PSObject> psObjects = pipeline.Invoke();
        foreach (var psObject in psObjects)
        {
            WriteObject(psObject);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是尝试在PowerShell中执行此CmdLet会给我这个错误:术语Import-Module不被识别为cmdlet的名称.PowerShell中的相同命令不会给我这个错误.如果我执行'Get-Command',我可以看到'Invoke-Module'被列为CmdLet.

有没有办法在Runspace中执行'Import-Module'?

谢谢!

x0n*_*x0n 22

有两种方法可以以编程方式导入模块,但我会首先解决您的方法.您的行pipeline.Commands.Add("...")应该只添加命令,而不是命令AND参数.该参数单独添加:

# argument is a positional parameter
pipeline.Commands.Add("Import-Module");
var command = pipeline.Commands[0];
command.Parameters.Add("Name", @"G:\PowerShell\PowerDbg.psm1")
Run Code Online (Sandbox Code Playgroud)

上面的管道API使用起来有点笨拙,并且在许多用途中被非正式地弃用,尽管它是许多更高级API的基础.在PowerShell v2或更高版本中执行此操作的最佳方法是使用System.Management.Automation.PowerShellType及其流畅的API:

# if Create() is invoked, a runspace is created for you
var ps = PowerShell.Create(myRS);
ps.Commands.AddCommand("Import-Module").AddArgument(@"g:\...\PowerDbg.psm1")
ps.Invoke()
Run Code Online (Sandbox Code Playgroud)

使用后一种方法的另一种方法是使用InitialSessionState预加载模块,这样就不需要明确地为运行空间设置种子Import-Module.请参阅我的博客,了解如何执行此操作:

http://nivot.org/nivot2/post/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule.aspx

http://nivot.org/blog/post/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule

希望这可以帮助.

  • 谢谢!但方法Add()返回void.我想你需要使用一个Command对象并向其添加一个参数并将其传递给Add方法.您正在谈论以编程方式执行此操作的两种方法,第二种方法是什么? (2认同)
  • https://web.archive.org/web/20190330193827/http://nivot.org/blog/post/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule (2认同)