Skip to content

Instantly share code, notes, and snippets.

@JeffMill
Last active April 22, 2025 23:07
Show Gist options
  • Save JeffMill/df82ee48f6eb87da5aac17cb66a2003b to your computer and use it in GitHub Desktop.
Save JeffMill/df82ee48f6eb87da5aac17cb66a2003b to your computer and use it in GitHub Desktop.
Pipe powershell command output to C# program
using System.Diagnostics;
using System.Text;
using (Process process = new Process())
{
int timeoutMS = 1000;
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.Arguments = "-NoLogo -NoProfile -NonInteractive -Command \"&{ Get-DeliveryOptimizationLog }\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
StringBuilder output = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
// Output data stream complete.
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
if (process.WaitForExit(timeoutMS) && outputWaitHandle.WaitOne(timeoutMS))
{
// Process completed, and output data stream complete.
}
else
{
// Timed out.
}
}
Console.WriteLine("--- output start ---");
Console.WriteLine(output);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment