簡體   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