用C#读取Powershell进度条输出

我有一个程序从事件处理程序调用powershell脚本。 powershell脚本由第三方提供,我对它没有任何控制权。

powershell脚本使用powershell进度条。 我需要阅读powershell脚本的进度,但是由于进度条,System.Management.Automation命名空间不会将其视为输出。 是否可以从外部程序中读取powershell进度条的值?

Process process = new Process();

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

您需要将DataAdded事件的事件处理程序添加到PowerShell实例的Progress流 :

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

(你当然可以在我的例子中使用委托或常规事件处理程序替换lambda表达式)