简体   繁体   中英

Reading Powershell Progress Bar Output in C#

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.

The powershell script uses the powershell progress bar. I need to read the progress of the powershell script, however because of the progress bar the System.Management.Automation namespaces do not consider this as output. Is it possible to read the value of the powershell progress bar from an external program?

Process process = new Process();

  process.StartInfo.FileName = "powershell.exe"; process.StartInfo.Arguments = String.Format("-noexit -file \\"{0}\\"", scriptFilePath); process.Start(); 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM