我正在實現一個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
類的例子很少,而且我完全不瞭解線程,所以任何幫助都將不勝感激。