Please feel free to provide feedback or file bugs here.

[BUG] Start-Process might not return Handle/ExitCode

Issue:
In order to obtain the Exit Code from a Process we are executing the Start-Process cmdlet with the following parameters:
-PassThru -Wait -WindowStyle Hidden
or
-PassThru -Wait -NoNewWindow

In rare cases, this leads to the following exception:
System.Management.Automation.CmdletInvocationException: Cannot process request because the process (<ProcessIdHere>) has exited. ---> System.InvalidOperationException: Cannot process request because the process (<ProcessIdHere>) has exited.
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.OpenProcessHandle(Int32 access)
at System.Diagnostics.Process.get_Handle()

After the Exception occurred, the returned Object does not contain a Handle nor Exit Code but the executable itself executed without issue.

We also tried to remove the “-Wait” Parameter and use the $process.WaitForExit() Method without success (as proposed here: https://stackoverflow.com/questions/44057728/start-process-system-diagnostics-process-exitcode-is-null-with-nonewwindow and https://stackoverflow.com/questions/10262231/obtaining-exitcode-using-start-process-and-waitforexit-instead-of-wait).

This happens on Windows 7 and Windows 10 Clients.
When the issue occurs, it is mostly when running small and low footprint executables like reg.exe.

Possible Cause:
This error is probably caused by the fact, that the process which was opened by Start-Process has already finished (and thereby is already killed) when Start-Process tries to get the handle.

Example:
$process = Start-Process -PassThru -Wait -NoNewWindow -FilePath “C:\Windows\System32\reg.exe” -ArgumentList “import C:\temp\dummy.reg”

1. Start-Process executes “reg.exe”
2. “reg.exe” terminates, before Start-Process is able to get the handle (get_Handle Method)
3. Start-Process throws a System.InvalidOperationException Exception

PowerShell Environment:
PSVersion 5.1.16299.666

Is it possible to fix the behavior of Start-Process in order to get consistent results?

3 votes
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    Signed in as (Sign out)

    We’ll send you updates on this idea

    Roman Schraner shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    0 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      Signed in as (Sign out)
      Submitting...

      Feedback and Knowledge Base