2016-07-14 248 views
2

當我在C#中調用powershell命令時,如何運行前體命令(例如set-adserversettings)?現在它返回0個結果。運行多個powershell命令

這裏是我使用的代碼:

Command command1 = new Command("set-adserversettings"); 
CommandParameter parameter1 = new CommandParameter("viewentireforest", true); 
command1.Parameters.Add(parameter1); 

Command command2 = new Command("set-userphoto"); 
CommandParameter parameter2a = new CommandParameter("identity", tbxName.Text); 
CommandParameter parameter2b = new CommandParameter("picturedata", displayedImage); 
CommandParameter parameter2c = new CommandParameter("domaincontroller", "xx-xx-xx-01.xx.xx.xx.xxx"); 
CommandParameter parameter2d = new CommandParameter("confirm", false); 
command2.Parameters.Add(parameter2a); 
command2.Parameters.Add(parameter2b); 
command2.Parameters.Add(parameter2c); 
command2.Parameters.Add(parameter2d); 

Pipeline pipeline = runspacee.CreatePipeline(); 

pipeline.Commands.Add(command1); 
pipeline.Commands.Add(command2); 

var exResults = pipeline.Invoke(); 
+0

什麼你能在PoSh中,你無法使用.Net? –

回答

1

我測試後,它的工作如下,你應該運行在不同的管道,但繼續這些命令:

List<Command> commandList = new List<Command>(); 

    Command command1 = new Command("set-adserversettings"); 
    CommandParameter parameter1 = new CommandParameter("viewentireforest", true); 
    command1.Parameters.Add(parameter1); 
    commandList.Add(command1); 

    Command command2 = new Command("set-userphoto"); 
    CommandParameter parameter2a = new CommandParameter("identity", tbxName.Text); 
    CommandParameter parameter2b = new CommandParameter("picturedata", displayedImage); 
    CommandParameter parameter2c = new CommandParameter("domaincontroller", "xx-xx-xx-01.xx.xx.xx.xxx"); 
    CommandParameter parameter2d = new CommandParameter("confirm", false); 
    command2.Parameters.Add(parameter2a); 
    command2.Parameters.Add(parameter2b); 
    command2.Parameters.Add(parameter2c); 
    command2.Parameters.Add(parameter2d); 
    commandList.Add(command2); 

    Pipeline pipeline; 
    Collection<PSObject> exResults = null; 

    foreach (Command cmd in commandList) 
    { 
     pipeline = runspacee.CreatePipeline(); 
     pipeline.Commands.Add(cmd); 

     exResults = pipeline.Invoke(); 
    } 
+0

真的很棒的發現 - 我正在拉我的頭髮,試圖找出爲什麼叫Powershell.Invoke()確實忽略set-adserversettings。迭代通過Powershell.Commands,爲每個命令創建一個管道最終確實使它工作。我不知道爲什麼幾乎沒有人似乎有這個問題... – Compufreak

+0

也許這是一個壞主意,以處理在.NET代碼中的PowerShell命令。如果官方有更完整的圖書館來幫助我處理,我會馬上使用它。 –