我有一個在 PowerShell 中運行并不斷回傳結果的命令(實際上是一個 DAPR 命令 :-) )。我知道如何連接到 PowerShell 終端并獲得結果,但我的問題是我的命令不斷回傳結果,我需要將此結果捕獲到表單中。
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.AddScript("ping 172.21.1.25 -t");
powerShell.AddCommand("Out-String");
Collection<PSObject> PSOutput = powerShell.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject pSObject in PSOutput)
{
stringBuilder.AppendLine(pSObject.ToString());
}
return stringBuilder.ToString();
}
uj5u.com熱心網友回復:
您無需等待管道回傳 - 您可以在它仍在運行時開始使用輸出!
您只需要進行一些更改:
- 將
-Streamswitch 引數添加到Out-String(或Out-String完全洗掉) - 創建一個
PSDataCollection<string>實體,通過它我們可以收集輸出 - 異步呼叫管道,使用
PowerShell.BeginInvoke<TInput, TOutput>()
void PingForever()
{
using (var powerShell = PowerShell.Create())
{
// prepare commands - notice we use `Out-String -Stream` to avoid "backing up" the pipeline
powerShell.AddScript("ping 8.8.8.8 -t");
powerShell.AddCommand("Out-String").AddParameter("Stream", true);
// now prepare a collection for the output, register event handler
var output = new PSDataCollection<string>();
output.DataAdded = new EventHandler<DataAddedEventArgs>(ProcessOutput);
// invoke the command asynchronously - we'll be relying on the event handler to process the output instead of collecting it here
var asyncToken = powerShell.BeginInvoke<object,string>(null, output);
if(asyncToken.AsyncWaitHandle.WaitOne()){
if(powerShell.HadErrors){
foreach(var errorRecord in powerShell.Streams.Error){
// inspect errors here
// alternatively: register an event handler for `powerShell.Streams.Error.DataAdded` event
}
}
// end invocation without collecting output (event handler has already taken care of that)
powerShell.EndInvoke(asyncToken);
}
}
}
void ProcessOutput(object? sender, DataAddedEventArgs eventArgs)
{
var collection = sender as PSDataCollection<string>;
if(null != collection){
var outputItem = collection[eventArgs.Index];
// Here's where you'd update the form with the new output item
Console.WriteLine("Got some output: '{0}'", outputItem);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385972.html
