Last active
April 22, 2025 23:07
-
-
Save JeffMill/df82ee48f6eb87da5aac17cb66a2003b to your computer and use it in GitHub Desktop.
Pipe powershell command output to C# program
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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