Created
January 3, 2012 14:11
-
-
Save haf/1555015 to your computer and use it in GitHub Desktop.
Console output with C#
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; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
using System.Threading; | |
namespace ConsoleApplication1 | |
{ | |
class App | |
{ | |
static int Main(string[] args) | |
{ | |
Console.WriteLine("sh64 args: " + string.Join(", ", args)); | |
var start = new ProcessStartInfo | |
{ | |
FileName = args.First(), | |
Arguments = string.Join(" ", args.Skip(1).ToArray()), | |
UseShellExecute = false, | |
RedirectStandardOutput = true, | |
RedirectStandardError = true, | |
RedirectStandardInput = false, | |
CreateNoWindow = true | |
}; | |
using (var process = Process.Start(start)) | |
{ | |
while (!process.HasExited) | |
{ | |
using (var reader = process.StandardOutput) | |
Drain(reader, false); | |
using (var reader = process.StandardError) | |
Drain(reader, true); | |
} | |
process.WaitForExit(); | |
return process.ExitCode; | |
} | |
} | |
static void Drain(TextReader reader, bool error) | |
{ | |
ColourizeError(error, () => | |
{ | |
var buf = new char[256]; | |
int read; | |
while ((read = reader.Read(buf, 0, buf.Length)) != 0) | |
Console.Write(new string(buf, 0, read)); | |
}); | |
} | |
static void ColourizeError(bool error, Action a) | |
{ | |
var prev = Console.ForegroundColor; | |
Console.ForegroundColor = error ? ConsoleColor.Red : ConsoleColor.White; | |
var mre = new ManualResetEventSlim(false); | |
try | |
{ | |
a(); | |
} | |
finally | |
{ | |
Console.ForegroundColor = prev; | |
mre.Set(); // runs on GC thread on servers and is reentrant/interleaved concurrency in workstations! | |
} | |
mre.Wait(); | |
} | |
} | |
} |
This will wrap 64 bit powershell commands properly, including stderr and stdout, interleaved (to some extent at least, interleaving in a not-so-nice-way might occurr)
This solves this error:
No snap-ins have been registered for Windows PowerShell version 2
by running powershell w/ a 64-bit executable.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
csc /out:"buildscripts\sh64.exe" .\buildscripts\sh64.cs /platform:x64