4

I have a program that is calling a powershell script from an event handler. The powershell script is provided by a third party, and I do not have any control over it.

The powershell script uses the powershell progress bar. I need to read the progress of the powershell script, however because of the progress bar the System.Management.Automation namespaces do not consider this as output. Is it possible to read the value of the powershell progress bar from an external program?

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

process.Start();
3
  • Is the script running as a standalone or within the Powershell ISE? Also, do you need to know moment-by-moment the value, or do you only care when it has reached 100%? Commented Jan 15, 2016 at 15:59
  • moment by moment. I am currently starting it via the edit I have made in the above. Commented Jan 15, 2016 at 16:09
  • 1
    If you want some programmatic control over the Progress stream, don't start powershell.exe, use System.Management.Automation instead Commented Jan 15, 2016 at 16:10

1 Answer 1

7

You need to add an event handler for the DataAdded event to the Progress stream of your PowerShell instance:

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();
}

(you can of course substitute the lambda expression in my example with a delegate or a regular event handler should you want to)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.