c#执行powershell并异步读取stdout

时间:2015-01-01 06:12:52

标签: c#

我和Powershell/C#: Invoking a pipeline asynchronously & displaying the results

有同样的问题

我希望在c#中获得System.Management.Automation.Powershell的stdout和stderror 并且在GUI执行时将其显示在GUI上,因为该过程非常漫长,我需要主动显示正在发生的事情。 它没有启动我已经添加的处理程序。 我已经提出了分数...... 任何想法为什么它没有解雇?

delegate void SetOutput(string value);
PowerShell ps;

private void LocalExec()
{
    string script = "ls C:\";
    Collection<PSObject> results = null;
    ps = PowerShell.Create();
    ps.AddScript(script);
    ps.Streams.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(Verbose_DataAdded);
    IAsyncResult res = ps.BeginInvoke<PSObject>(null, null, AsyncInvoke, null);
}

void AsyncInvoke(IAsyncResult res)
{
    try
    {
        ps.EndInvoke(res);
    }
    catch (Exception ex)
    {
    }
}

private void PsDataAdded(object sender, DataAddedEventArgs e)
{
    string msg = ((PSDataCollection<VerboseRecord>)sender)[e.Index].ToString();
    Console.WriteLine(msg);
}

void Verbose_DataAdded(object sender, DataAddedEventArgs e)
{
    System.Diagnostics.Debug.Print(((PSDataCollection<VerboseRecord>)sender)[e.Index].ToString());

    if (txtOutput.InvokeRequired)
    {
        string msg = ((PSDataCollection<VerboseRecord>)sender)[e.Index].ToString();
        txtOutput.Invoke(new SetOutput(Execute), new object[] { msg });
    }
}

private void Execute(string msg)
{
    txtOutput.AppendText(msg);
    txtOutput.ScrollToCaret();
}

0 个答案:

没有答案