执行连续运行的 PowerShell 命令并将结果放入表单中

MH2*_*538 0 c# powershell winforms

我有一个在 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();
        }
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 6

您无需等待管道返回 - 您可以在管道仍在运行时开始消耗输出!

您只需要进行一些更改:

  • 添加-Stream开关参数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);
    }
}
Run Code Online (Sandbox Code Playgroud)