Fix Start-Process -PassThru to make sure the ExitCode property is accessible for the returned Process object (#20749) (#20866)

This commit is contained in:
Dongbo Wang
2023-12-07 21:39:08 -08:00
committed by GitHub
parent 29fa9dfabd
commit 851d21b673
2 changed files with 12 additions and 0 deletions
@@ -2126,6 +2126,13 @@ namespace Microsoft.PowerShell.Commands
jobAssigned = jobObject.AssignProcessToJobObject(processInfo.Process);
}
// Since the process wasn't spawned by .NET, we need to trigger .NET to get a lock on the handle of the process.
// Otherwise, accessing properties like `ExitCode` will throw the following exception:
// "Process was not started by this object, so requested information cannot be determined."
// Fetching the process handle will trigger the `Process` object to update its internal state by calling `SetProcessHandle`,
// the result is discarded as it's not used later in this code.
_ = process.Handle;
// Resume the process now that is has been set up.
processInfo.Resume();
#endif
@@ -115,6 +115,11 @@ Describe "Start-Process" -Tag "Feature","RequireAdminOnWindows" {
{ Start-Process -FilePath $pingCommand -NoNewWindow -WindowStyle Normal -ErrorAction Stop } | Should -Throw -ErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand"
}
It "ExitCode returns with -NoNewWindow, -PassThru and -Wait" {
$process = Start-Process -FilePath $pingCommand -ArgumentList $pingParam -NoNewWindow -PassThru -Wait -ErrorAction Stop
$process.ExitCode | Should -Be 0
}
It "Should start cmd.exe with Verb 'open' and WindowStyle 'Minimized'" -Skip:(!$isFullWin) {
$fileToWrite = Join-Path $TestDrive "VerbTest.txt"
$process = Start-Process cmd.exe -ArgumentList "/c echo abc > $fileToWrite" -Verb open -WindowStyle Minimized -PassThru