Reading Powershell Progress Bar Output in C#

前端 未结 1 372
南方客
南方客 2021-01-23 01:23

I have a program that is calling a powershell script from an event handler. The powershell script is provided by a third party, and I do not have any control over it.

T

相关标签:
1条回答
  • 2021-01-23 01:34

    You need to add an event handler for the DataAdded event to the Progress stream of your PowerShell instance:

    using (PowerShell psinstance = PowerShell.Create())
    { 
        psinstance.AddScript(@"C:\3rd\party\script.ps1");
        psinstance.Streams.Progress.DataAdded += (sender,eventargs) => {
            PSDataCollection<ProgressRecord> progressRecords = (PSDataCollection<ProgressRecord>)sender;
            Console.WriteLine("Progress is {0} percent complete", progressRecords[eventargs.Index].PercentComplete);
        };
        psinstance.Invoke();
    }
    

    (you can of course substitute the lambda expression in my example with a delegate or a regular event handler should you want to)

    0 讨论(0)
提交回复
热议问题