PowerShell 3.0 behavior when getting external process exit code
I have been using this code from another post from this site:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo $pinfo.FileName = "notepad.exe" $pinfo.RedirectStandardError = $true $pinfo.RedirectStandardOutput = $true $pinfo.UseShellExecute = $false $pinfo.Arguments = "" $p = New-Object System.Diagnostics.Process $p.StartInfo = $pinfo **$p.Start() | Out-Null** #Do Other Stuff Here.... **$p.WaitForExit()** $p.ExitCode
It has worked fine under PowerShell 2.0. The server was upgraded to PowerShell 3.0, and now the two bold like fail with:
Exception calling "Start" with "0" argument(s): "The system cannot find the file specified" At \\asdnsom3978\optim_windows\script_master\exportall.ps1:126 char:1 + $p.Start() | Out-Null + ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) , MethodInvocationException + FullyQualifiedErrorId : Win32Exception Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object." At \\asdnsom3978\optim_windows\script_master\exportall.ps1:128 char:1 + $p.WaitForExit() + ~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) , MethodInvocationException + FullyQualifiedErrorId : InvalidOperationException
Why did it broke and how do I correct it so it works for both version 2.0 and 3.0?
Hmm, I can't repro the error on my V3 system. But why are you going to all this trouble when you can just use the Start-Process command to do this e.g.:
$p = Start-Process Notepad -Wait -PassThru $p.ExitCode
You might want to try providing a fully-qualified path to notepad.exe, like "C:\Windows\notepad.exe".