在 C# 中读取 Powershell 进度条输出

use*_*406 3 c# powershell

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

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

进程进程=新进程();

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

        process.Start();
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 5

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

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();
}
Run Code Online (Sandbox Code Playgroud)

(如果您愿意,您当然可以用委托或常规事件处理程序替换我示例中的 lambda 表达式)