Interesting Effect (bug) with Consoles and Processes.
February 11th, 2010 by KarlI was having an odd behavior with Portable PowerShell where if i started it from CMD it would take turns between giving a CMD.exe prompt and a PowerShell Prompt and take turns running them.
So in this test app, you can see we are first in CMD, then we run this application then after than its alternating between CMD and PowerShell Prompts and you see the expression 1 worked in PowerShell while having a problem in CMD.EXE
So i hear you say what’s the source code for this little demo? – I’m glad you asked
class Program
{
static void Main(string[] args)
{
var p = new System.Diagnostics.ProcessStartInfo("powershell");
p.UseShellExecute = false;
System.Diagnostics.Process.Start(p);
}
}
So why is this happening. Well normally when a console application calls another and they run using the same console window the first one is effectively paused while the 2nd one is running, then when the 2nd one exits it resumes.
so the flow here if it were working would be
CMD –> TESTAPP –> POWERSHELL
CMD naturally is waiting for testapp to exit, then in the sample code TESTAPP starts powershell, but i forgot to waitfor powershell to exit before proceding, so TestApp and PowerShell are sharing the same console for a split second then TestAPP Exits, and when TestApp exits CMD regains control of the console.. Now you have too totally separate programs CMD and POWERSHELL competing and using the same physical console window.
The fix is really simple.
.
class Program
{
static void Main(string[] args)
{
var p = new System.Diagnostics.ProcessStartInfo("powershell");
p.UseShellExecute = false;
var proc = System.Diagnostics.Process.Start(p);
proc.WaitForExit();
}
}
Not really a biggie, but i thought it would be an interesting thing to share, and probably the cause of a bit of hair pulling by many.
Posted in Portable PowerShell, Powershell | No Comments »
