2011-06-07 112 views
12


我想在C#中創建一個cmdlet。該代碼看起來是這樣的:PowerShell - 如何在運行空間導入模塊

[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); 
     } 
    } 
} 

但試圖執行此cmdlet在PowerShell中給了我這個錯誤:術語導入模塊不被識別爲cmdlet的名稱。 PowerShell中的相同命令不會給我這個錯誤。如果我執行'Get-Command',我可以看到'Invoke-Module'被列爲CmdLet。

有沒有辦法在運行空間中執行「導入模塊」?

謝謝!

回答

18

有兩種方法可以以編程方式導入模塊,但我會先解決您的方法。您的行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") 

上述管道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明確。見我的博客在這裏如何做到這一點:

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

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

希望這有助於。

+2

謝謝!但Add()方法返回void。我想你需要使用一個Command對象並向它添加一個參數並將其傳遞給Add方法。您正在談論以兩種方式進行編程,第二種方式是什麼? – Absolom 2011-06-07 15:28:10

+0

oops,以第二種方式更新答案。 – x0n 2011-06-07 15:33:59

+0

我還發現,如果您在嘗試導入模塊時遇到「AuthorizationManager檢查失敗」異常,請確保您的.psm1文件以UTF8格式保存,而不是以ASCII格式保存。 – Absolom 2011-06-07 15:34:06