2016-01-15 62 views
3

我有一個程序,從事件處理程序調用PowerShell腳本。 powershell腳本是由第三方提供的,我沒有任何控制權。閱讀PowerShell進度條輸出C#

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(); 
+0

腳本是作爲獨立運行還是作爲Powershell ISE運行?此外,您是否需要知道每一刻的價值,還是隻有當它達到100%時纔會關心? – Wossname

+0

每時每刻。我目前通過我在上面所做的編輯開始它。 – user3010406

+0

如果您想對Progress流進行一些編程控制,請不要啓動'powershell.exe',而應使用'System.Management.Automation' –

回答

4

您需要爲DataAdded事件添加事件處理程序到你的PowerShell實例的Progress stream

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表達式在我的例子有代表或者您想要的常規事件處理程序)