Note:
- The problem only surfaces on Windows.
- The problem does not occur when you use
-Wait in addition to -PassThru as opposed to a separate Wait-Process call.
Workaround:
Per #20716 (comment), the workaround is to cache the process handle before calling Wait-Process / .WaitForExit():
$p = Start-Process cmd -args '/c', 'ver' -PassThru -NoNewWindow
$dummy = $p.Handle # WORKAROUND: use a dummy variable to cache the handle
Wait-Process -id $p.Id
"Exit code: [$($p.ExitCode)]" # Now the exit code is reported.
Steps to reproduce
On Windows:
$p = Start-Process cmd -args '/c', 'ver' -PassThru -NoNewWindow
Wait-Process -id $p.Id
"Exit code: [$($p.ExitCode)]"
Note that the problem only occurs when -NoNewWindows and /or any of the -RedirectStandard* parameters are present.
Inserting a $p.WaitForExit() call after the Wait-Process call, as suggested in the docs to ensure that .ExitCode has a value (which should be the equivalent of Wait-Process), doesn't help.
Expected behavior
Microsoft Windows [Version 10.0.15063]
Exit code: [0]
$ps.ExitCode should contain 0, given that the cmd command reports exit code 0.
Actual behavior
Microsoft Windows [Version 10.0.15063]
Exit code: []
Note how $ps.ExitCode is unexpectedly stringified to the empty string.
Also, even though Get-Member indicates that the property's date type is [int], $null -eq $ps.ExitCode is $true.
This suggests that an exception is occurring behind the scenes, which PowerShell quietly ignores.
An exception when accessing .ExitCode should only occur if the process hasn't exited yet, however, which is at odds with having used Wait-Process and $p.HasExited indicating $true.
Environment data
PowerShell Core v6.0.0-beta.9 on Microsoft Windows 10 Pro (64-bit; v10.0.15063)
Windows PowerShell v5.1.15063.674 on Microsoft Windows 10 Pro (64-bit; v10.0.15063)
Note:
-Waitin addition to-PassThruas opposed to a separateWait-Processcall.-Waitis used.Workaround:
Per #20716 (comment), the workaround is to cache the process handle before calling
Wait-Process/.WaitForExit():Steps to reproduce
On Windows:
Note that the problem only occurs when
-NoNewWindowsand /or any of the-RedirectStandard*parameters are present.Inserting a
$p.WaitForExit()call after theWait-Processcall, as suggested in the docs to ensure that.ExitCodehas a value (which should be the equivalent ofWait-Process), doesn't help.Expected behavior
$ps.ExitCodeshould contain0, given that thecmdcommand reports exit code0.Actual behavior
Note how
$ps.ExitCodeis unexpectedly stringified to the empty string.Also, even though
Get-Memberindicates that the property's date type is[int],$null -eq $ps.ExitCodeis$true.This suggests that an exception is occurring behind the scenes, which PowerShell quietly ignores.
An exception when accessing
.ExitCodeshould only occur if the process hasn't exited yet, however, which is at odds with having usedWait-Processand$p.HasExitedindicating$true.Environment data