Skip to content

Commit

Permalink
Fix Start-Process -PassThru to make sure the ExitCode property is…
Browse files Browse the repository at this point in the history
… accessible for the returned `Process` object (#20749) (#20866)
  • Loading branch information
daxian-dbw committed Dec 8, 2023
1 parent 29fa9df commit 851d21b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
Expand Up @@ -2126,6 +2126,13 @@ protected override void BeginProcessing()
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
Expand Down
Expand Up @@ -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
Expand Down

0 comments on commit 851d21b

Please sign in to comment.