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

C# 在C中读取Powershell进度条输出#,c#,powershell,C#,Powershell,我有一个程序正在从事件处理程序调用powershell脚本。powershell脚本由第三方提供,我无法控制它 powershell脚本使用powershell进度条。我需要阅读PosithScript脚本的进度,但是由于进度条,Soal.MaultMalk.AutoScript名称空间不考虑这是输出。是否可以从外部程序读取powershell进度条的值 流程=新流程() 您需要将DataAdded事件的事件处理程序添加到PowerShell实例的: using (PowerShell psin

我有一个程序正在从事件处理程序调用powershell脚本。powershell脚本由第三方提供,我无法控制它

powershell脚本使用powershell进度条。我需要阅读PosithScript脚本的进度,但是由于进度条,Soal.MaultMalk.AutoScript名称空间不考虑这是输出。是否可以从外部程序读取powershell进度条的值

流程=新流程()


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

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();
}
使用(PowerShell pInstance=PowerShell.Create())
{ 
pInstance.AddScript(@“C:\3rd\party\script.ps1”);
psinstance.Streams.Progress.DataAdded+=(发送方,事件参数)=>{
PSDataCollection progressRecords=(PSDataCollection)发送方;
WriteLine(“进度为{0}完成百分比”,progressRecords[eventargs.Index].PercentComplete);
};
psinstance.Invoke();
}

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

脚本是作为独立脚本运行还是在Powershell ISE中运行?此外,你是否需要一刻一刻地了解价值,还是只关心它何时达到100%?一刻一刻地。我目前正在通过上面所做的编辑来启动它。如果您希望对进度流进行编程控制,请不要启动
powershell.exe
,而是使用
System.Management.Automation
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();
}