From 7fe5cb3e354eb775778944e5419cfbcb8fede735 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 2 Feb 2023 16:15:53 -0800 Subject: [PATCH] Fix `Start-Process -Credential -Wait` to work on Windows (#19082) * address Ilya's feedback, simplify to just WaitForExit() when cred is used * Update src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs Co-authored-by: Ilya --------- Co-authored-by: Ilya --- .../commands/management/Process.cs | 34 ++++++++++++------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 2bdb5fcc2b..70596e263d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -2039,22 +2039,30 @@ namespace Microsoft.PowerShell.Commands #if UNIX process.WaitForExit(); #else - _waithandle = new ManualResetEvent(false); - - // Create and start the job object - ProcessCollection jobObject = new(); - if (jobObject.AssignProcessToJobObject(process)) + if (_credential is not null) { - // Wait for the job object to finish - jobObject.WaitOne(_waithandle); - } - else if (!process.HasExited) - { - // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. - process.Exited += myProcess_Exited; - process.EnableRaisingEvents = true; + // If we are running as a different user, we cannot use a job object, so just wait on the process process.WaitForExit(); } + else + { + _waithandle = new ManualResetEvent(false); + + // Create and start the job object + ProcessCollection jobObject = new(); + if (jobObject.AssignProcessToJobObject(process)) + { + // Wait for the job object to finish + jobObject.WaitOne(_waithandle); + } + else if (!process.HasExited) + { + // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. + process.Exited += myProcess_Exited; + process.EnableRaisingEvents = true; + process.WaitForExit(); + } + } #endif } }