繁体   English   中英

PowerShell - 如何在运行空间中导入模块

[英]PowerShell - How to Import-Module in a Runspace


我正在尝试在 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);
        }
    }
}

但是尝试在 PowerShell 中执行这个 CmdLet 给我这个错误:术语 Import-Module is not Recognized as the name of a cmdlet PowerShell 中的相同命令不会给我这个错误。 如果我改为执行“Get-Command”,我可以看到“Invoke-Module”被列为 CmdLet。

有没有办法在运行空间中执行“导入模块”?

谢谢!

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

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

上面的管道 API 使用起来有点笨拙,尽管它是许多更高级别 API 的基础,但在许多用途中被非正式地弃用。 在 powershell v2 或更高版本中执行此操作的最佳方法是使用System.Management.Automation.PowerShell类型及其流畅的 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()

使用后一种方法的另一种方法是使用 InitialSessionState 预加载模块,这避免了使用Import-Module显式播种运行空间的需要。

InitialSessionState initial = InitialSessionState.CreateDefault();
    initialSession.ImportPSModule(new[] { modulePathOrModuleName1, ... });
    Runspace runspace = RunspaceFactory.CreateRunspace(initial);
    runspace.Open();
    RunspaceInvoke invoker = new RunspaceInvoke(runspace);
    Collection<PSObject> results = invoker.Invoke("...");

希望这可以帮助。

最简单的方法是使用AddScript()方法。 你可以做:

pipeline.AddScript("Import-Module moduleName").Invoke();

如果要在同一行中添加另一个导入

pipeline.AddScript("Import-Module moduleName \n Import-Module moduleName2").Invoke();

.Invoke()在您将脚本添加到管道后,它不是强制性的,您可以添加更多脚本并稍后调用。

pipeline.AddScript("Import-Module moduleName");
pipeline.AddCommand("pwd");
pipeline.Invoke();

更多信息请访问微软官网

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM