2012-06-27 27 views
4

我正在實現一個WPF應用程序,該應用程序使用該對作爲腳本參數爲字典中給出的每個鍵/值對執行PowerShell腳本。我將每次運行的腳本作爲新命令存儲在流水線中。但是,這使得我只能從運行的最後一個命令中得到輸出,當我在腳本的每次運行後需要輸出時。每次腳本執行時我都考慮過創建一個新的管道,但是我需要知道腳本的所有執行何時完成。下面是相關的代碼,以幫助解釋我的問題:在執行每個管道命令後在C#中捕獲PowerShell輸出

private void executePowerShellScript(String scriptText, Dictionary<String, String> args) 
{ 
    // Create the PowerShell object. 
    PowerShell powerShell = PowerShell.Create(); 

    // If arguments were given, add the script and its arguments. 
    if (args != null) 
    { 
      foreach (KeyValuePair<String, String> arg in args) 
      { 
       powerShell.AddScript(scriptText); 
       powerShell.AddArgument(arg.Key); 
       powerShell.AddArgument(arg.Value); 
      } 
    } 

    // Otherwise, just add the script. 
    else 
      powerShell.AddScript(scriptText); 

    // Add the event handlers. 
    PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); 
    output.DataAdded += new EventHandler<DataAddedEventArgs>(Output_DataAdded); 
    powerShell.InvocationStateChanged += 
      new EventHandler<PSInvocationStateChangedEventArgs>(Powershell_InvocationStateChanged); 

    // Invoke the pipeline asynchronously. 
    IAsyncResult asyncResult = powerShell.BeginInvoke<PSObject, PSObject>(null, output); 
} 

private void Output_DataAdded(object sender, DataAddedEventArgs e) 
{ 
    PSDataCollection<PSObject> myp = (PSDataCollection<PSObject>)sender; 

    Collection<PSObject> results = myp.ReadAll(); 
    foreach (PSObject result in results) 
    { 
      Console.WriteLine(result.ToString()); 
    } 
} 

然後我用下面的方法時,腳本的所有執行已完成就知道了。因爲我做這通過檢查管道的調用狀態完成,我不能讓一個新的管道爲腳本的每次執行:

private void Powershell_InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e) 
{ 
    switch (e.InvocationStateInfo.State) 
    { 
      case PSInvocationState.Completed: 
       ActiveCommand.OnCommandSucceeded(new EventArgs()); 
       break; 
      case PSInvocationState.Failed: 
       OnErrorOccurred(new ErrorEventArgs((sender as PowerShell).Streams.Error.ReadAll())); 
       break; 
    } 
    Console.WriteLine("PowerShell object state changed: state: {0}\n", e.InvocationStateInfo.State); 
} 

因此,要獲得我的問題:

1)我可以在執行每條命令後強制管道產生輸出嗎?或者,
2)如果我每次運行命令時都要創建一個新的管道,還有另一種方法可以檢查腳本的所有執行是否已完成?

在C#中使用實際的PowerShell類的例子很少,而且我完全不瞭解線程,所以任何幫助都將不勝感激。

回答

3

我對回答自己的問題感到無聊,但我所做的只是將循環功能從我的C#代碼移到我的腳本中,並且工作正常。所以現在我將所有的鍵和值一次傳遞給數組參數,並且只有一個命令在管道中。

儘管如此,我仍然有興趣知道是否可以在管道中的每個命令執行後產生輸出。

0

我有一種情況,我有一個對象來管理PowerShell環境,它需要一個腳本或模塊和cmdlet並執行它,然後從原始模塊中獲取一個新的腳本或模塊以及cmdlet或cmdlet並執行它。每次執行某項操作時,都需要返回結果。我通過在每次執行後清除命令隊列來解決它:

powerShellInstance.Commands.Clear(); 

希望這有助於。

相關問題