Varun Gupta
Varun Gupta

Reputation: 1457

Wait for command to complete before executing next command in powershell

I have a powershell script were I need to execute first to invoke .cmd file to complete a network download and then I need to process on that downloaded data. Below is my command

Runas /savecred /profile /user:myuser "cmd /c C:\Users\myuser\myfile.cmd"
ECHO $Hello

From the above command, myfile.cmd downloads a file and then I need to process it. Here powershell does not waits for the file to download and starts executing below commands. How can I make it wait for the file to download?

Upvotes: 1

Views: 8845

Answers (2)

Luc VdV
Luc VdV

Reputation: 1198

Runas.exe doesn't wait for its child process to exit, so there is no straight-forward way to do this.

There are workarounds using SysInternals' pslist or something similar in a loop, but those solutions will derail if there's more than one process with the same name.

Something along this line:

runas /savecred /profile /user:user "X:\Path\MyProgram.exe"
do {
    Start-Sleep -Seconds 1
    pslist MyProgram >$null 2>&1
} while ($LASTEXITCODE -eq 0)

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200483

You need to wait for runas:

$cmd  = 'runas'
$args = '/savecred','/profile','/user:myuser','cmd /c C:\Users\myuser\myfile.cmd'
Start-Process $cmd $args -Wait

Upvotes: 0

Related Questions