Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8087149
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T18:40:49+00:00 2026-06-05T18:40:49+00:00

I have a similar, but different, question like How to redirect Powershell output from

  • 0

I have a similar, but different, question like How to redirect Powershell output from a script run by TaskScheduler and override default width of 80 characters.

I have a custom installer framework written long ago. Within it I can execute “tasks”. I recently had to add a task to execute a PowerShell script. Now, even though the task is written in C#, I cannot invoke the commands in the PowerShell script directly. That, unfortunately, is off the table.

In short, I want to invoke a PowerShell executable from C# and redirect its output back to my application. Here’s what I’ve done so far:

I can successfully invoke PowerShell using the following code (from a test project I created):

  string powerShellExeLocation = null;

  RegistryKey localKey = Registry.LocalMachine;

  RegistryKey subKey = localKey.OpenSubKey(@"SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine");
  powerShellExeLocation = subKey.GetValue("ApplicationBase").ToString();

  if (!Directory.Exists(powerShellExeLocation))
    throw new Exception("Cannot locate the PowerShell dir.");

  powerShellExeLocation = Path.Combine(powerShellExeLocation, "powershell.exe");

  if (!File.Exists(powerShellExeLocation))
    throw new Exception("Cannot locate the PowerShell executable.");

  string scriptLocation = Path.Combine(Environment.CurrentDirectory, "PowerShellScript.ps1");

  if (!File.Exists(scriptLocation))
    throw new Exception("Cannot locate the PowerShell script.");

  ProcessStartInfo processInfo = new ProcessStartInfo();
  processInfo.Verb = "runas";
  processInfo.UseShellExecute = false;
  processInfo.RedirectStandardOutput = true;
  processInfo.RedirectStandardOutput = true;
  processInfo.WorkingDirectory = Environment.CurrentDirectory;

  processInfo.FileName = powerShellExeLocation;
  processInfo.Arguments = "-NoLogo -OutputFormat Text -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + scriptLocation + "\" ";

  Process powerShellProcess = new Process();
  powerShellProcess.StartInfo = processInfo;
  powerShellProcess.OutputDataReceived += new DataReceivedEventHandler(powerShellProcess_OutputDataReceived);
  powerShellProcess.ErrorDataReceived += new DataReceivedEventHandler(powerShellProcess_ErrorDataReceived);

  powerShellProcess.Start();

  while (!powerShellProcess.HasExited)
  {
    Thread.Sleep(500);
  }

My handlers for the redirected output are never called:

void powerShellProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)

and

void powerShellProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)

I am fairly confident that the script is running. Right now I just have a test script that is outputting the PATH contents.

$a = $env:path; $a.Split(";")

I tested this from within a PowerShell instance and it outputs correctly.

What can I do to get the PowerShell output to redirect to my C# code? I don’t want to rely on the scripts that I will execute to handle their own logging. I’d rather gather their output and handle it within the framework’s logging mechanism.

EDIT
Realized I left the odd loop thing to wait for exit in that code example. I’ve had the process “WaitForExit”:

powerShellProcess.WaitForExit();

EDIT
Using the suggestion from @MiniBill. I came up with the following code snippit:

powerShellProcess.Start();
while (!powerShellProcess.HasExited)
{
  string line;
  while (!string.IsNullOrEmpty((line = powerShellProcess.StandardOutput.ReadLine())))
    this.LogInfo("PowerShell running: " + line);
}

This handles the output fine. It’s cutting my lines at 80 characters :(, but I can live with that unless someone else can provide a suggestion to fix that!

UPDATE A Solution

/*
  * The next few lines define the process start info for the PowerShell executable.
  */
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.WorkingDirectory = Environment.CurrentDirectory;

//this FileName was retrieved earlier by looking in the registry for key "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" and the value for "ApplicationBase"
processInfo.FileName = powerShellExeLocation;

//if we're going to use script arguments build up the arguments from the process start correctly.
if (!string.IsNullOrEmpty(this.ScriptArguments))
  processInfo.Arguments = "-NoLogo -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + ScriptLocation + "\" '" + ScriptArguments + "'";
else
  processInfo.Arguments = "-NoLogo -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + ScriptLocation + "\"";

//create the Process object, set the start info, and start the process
Process powerShellProcess = new Process();
powerShellProcess.StartInfo = processInfo;

powerShellProcess.Start();

/*
  * While the PowerShell process hasn't exited do the following:
  * 
  * Read from the current position of the StandardOutput to the end by each line and
  * update the tasks progress with this information
  * 
  * Read from the current position of StandardError to the end by each line, update
  * the task's progress with this information and set that we have an error.
  * 
  * Sleep for 250 milliseconds (1/4 of a sec)
  */
bool isError = false;
while (!powerShellProcess.HasExited)
{
  string standardOuputLine, standardErrorLine;
  while (!string.IsNullOrEmpty((standardOuputLine = powerShellProcess.StandardOutput.ReadLine())))
  {
    this.UpdateTaskProgress(standardOuputLine);
  }


  while (!string.IsNullOrEmpty((standardErrorLine = powerShellProcess.StandardError.ReadLine())))
  {
    this.UpdateTaskProgress(standardErrorLine);
    isError = true;
  }

  Thread.Sleep(250);
}

/*
  * Now that the process has completed read to the end of StandardOutput and StandardError.
  * Update the task progress with this information.
  */

string finalStdOuputLine = powerShellProcess.StandardOutput.ReadToEnd();
string finalStdErrorLine = powerShellProcess.StandardError.ReadToEnd();

if (!string.IsNullOrEmpty(finalStdOuputLine))
  this.UpdateTaskProgress(finalStdOuputLine);

if (!string.IsNullOrEmpty(finalStdErrorLine))
{
  this.UpdateTaskProgress(finalStdErrorLine);
  isError = true;
}

// there was an error during the run of PowerShell that was output to StandardError.  This doesn't necessarily mean that
// the script error'd but there was a problem.  Throw an exception for this.
if (isError)
  throw new Exception(string.Format(CultureInfo.InvariantCulture, "Error during the execution of {0}.", this.ScriptLocation));
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T18:40:50+00:00Added an answer on June 5, 2026 at 6:40 pm

    You want to use the Process.StandardOutput property. It’s a stream that you can open to get the program’s output

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

A question similar to Locating bundles by identifier , but different problem: I have
I have five tables that are fairly similar in structure but different enough that
I have seen a similar related post but my situation is a little different
I have a similar question than django cross-site reverse . But i think I
This is similar to another question (http://stackoverflow.com/questions/935556/mysql-dump-by-query) but I hope different enough. I want
My question is similar to this one , but is different enough that I
Note this is not a duplicate of this similar but different question ! My
I have a similar question here: Sphinx search ranking broken? , but thought I'd
Another Newbie question in XSLT transformation. (I have asked similar question before, but in
This is a similar question to those that have been asked before, but still

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.