2013-01-22 60 views
3

導入模塊命令與powershell窗口控制檯正常工作,但相同的命令不工作在C#API。 我使用這個項目執行PowerShell腳本:http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-CPowershell導入模塊命令不工作與c#api

它執行許多命令,但它不執行「導入模塊'c:\ vm \ vm.psd1'」命令。我嘗試導入微軟模塊,但它不起作用。我如何執行「導入模塊」命令與C#API?

p.s:「add-pssnapin'virtualmachinemanager'」不起作用。以這種方式

回答

1

嘗試加載模塊:

PowerShell powershell = PowerShell.Create(); 
powerShell.Commands.AddCommand("Import-Module").AddParameter("Name", "c:\vm\vm.psd1'"); 

PowerShell powershell = PowerShell.Create(); 
powershell.Commands.AddCommand("Add-PsSnapIn").AddParameter("Name", "virtualmachinemanager"); 

用一條管道將嘗試創建一個InitialSessionState

InitialSessionState iss = InitialSessionState.CreateDefault(); 
      iss.ImportPSModule(new string[] { @"C:\vm\vm.psd1"}); 
      Runspace runSpace = RunspaceFactory.CreateRunspace(iss); 
      runSpace.Open(); 

然後使用你的代碼pipeline從運行cmdlet的模塊加載

+0

pipeline.Commands.Add返回void。我使用諸如Command cmd = new Command(「Import-Module」); (新名稱CommandParameter(「Name」,@「C:\ Program Files \ Microsoft System Center 2012 \ Virtual Machine Manager \ bin \ psModules \ virtualmachinemanager \ virtualmachinemanager.psd1」)); pipeline.Commands.Add(cmd); '但它不起作用。 – Baris

+0

@Baris對不起,它適用於'Powershell'類..不在'pipeline'對象中。添加其他解決方案 –

+0

感謝您的回答,但我如何使用PowerShell類?我只使用管道執行命令。我嘗試使用PowerShell類,例如運行腳本之前:'PowerShell ps = PowerShell.Create(); ps.Commands.AddCommand(「Import-Module」) .AddParameter(「Name」, @「C:\ Program Files \ Microsoft System Center 2012 \ Virtual Machine Manager \ bin \ psModules \ virtualmachinemanager \ virtualmachinemanager.psd1」) ; ps.Invoke();'但它不起作用。我如何使用它? – Baris

1

嘗試是這樣的加載該管理單元和執行你的命令:

using System.Management.Automation.Runspaces; 

//... 

var rsConfig = RunspaceConfiguration.Create(); 
using (var myRunSpace = RunspaceFactory.CreateRunspace(rsConfig)) 
{ 
    PSSnapInException snapInException = null; 
    var info = rsConfig.AddPSSnapIn("FULL.SNAPIN.NAME.HERE", out snapInException); 

    myRunSpace.Open(); 
    using (var pipeLine = myRunSpace.CreatePipeline()) 
    { 
     Command cmd = new Command("YOURCOMMAND"); 
     cmd.Parameters.Add("PARAM1", param1); 
     cmd.Parameters.Add("PARAM2", param2); 
     cmd.Parameters.Add("PARAM3", param3); 

     pipeLine.Commands.Add(cmd); 
     pipeLine.Invoke(); 
     if (pipeLine.Error != null && pipeLine.Error.Count > 0) 
     { 
      //check error 
     } 
    } 
} 
+0

嗨,謝謝你的回答。我嘗試添加管理單元,但我沒有添加管理單元。 – Baris