0
votes

I am starting a process with PowerShell using another user with elevated rights.

$username = "username" 
$password = "password"
$startWithElevatedRights = "notepad"

$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ‘,  $startWithElevatedRights, ‘ -Wait -verb runas}'

I know it's bad style to write user credentials to code, but it is used within full automated procedures, so this is necessary. My problem is, that I cannot wait until the process (last code line) finished. The inner process waits as expected.

I tried the parameter -Wait, * | Wait-Process, * | Out-Null, with return Value (which is always null) Nothing works.

Is there any solution waiting until the process has exited? If there is any solution for PowerShell 2.0 it would be the best for my use case.

1
Do you need to start a new powershell process within the powershell process your script already executes in in order to start notepad? - arco444
Can you post the code where you have used the -Wait parameter? - DanL
@arco444 I don't need to start another PowerShell, but I need the elevated rights. Notepad is just a dummy in this case. - ToTr
@DanL I just tried it out everywhere within the line of Start-Process. After the credentials and before, after the complete argument list and within the argument list (between the ' chars)... - ToTr
I'm sorry, I forgot to add the working "wait" within the inner start-process. I edited my post to match the described problem. - ToTr

1 Answers

2
votes

You can get Process object from Start-Process using PassThru parameter and then wait for it to exit.

$username = "username" 
$password = "password"
$startWithElevatedRights = "notepad"

$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$ps = Start-Process -PassThru -FilePath powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ',  $startWithElevatedRights, ' -Wait -verb runas}'

$ps.WaitForExit()