[BUG] Start-Process might not return Handle/ExitCode
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
-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)
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.
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.
$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
Is it possible to fix the behavior of Start-Process in order to get consistent results?