繁体   English   中英

用C#读取Powershell进度条输出

[英]Reading Powershell Progress Bar Output in C#

我有一个程序从事件处理程序调用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(); 

您需要将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();
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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