Start-Process -wait doesn't work when script is launched from command prompt opened with runas or as a scheduled task

user3137716 picture user3137716 · Dec 26, 2013 · Viewed 18.8k times · Source

I've got a script that's I want to run as a scheduled task, but it's not doing the thing it's supposed to. I'm trying to call an executable with Start-Process and the -Wait switch before continuing. Line is

Start-Process -FilePath "C:\Pfx Engagement\Admin\Utilities\Backup Restore\BackupRestoreUtil.exe" -ArgumentList "/f "$backup_directory"" -Wait

If I call it from a command prompt, ie:

powershell .\script.ps1

it works. It runs the command and waits for it to finish before moving on. There's more to the script that has to be run after that command is finished. The problem is that when it's a scheduled task, it doesn't wait. Doing some basic troubleshooting, I first tried opening a cmd window with runas using the scheduled task account, named "Scripts." So I run

runas /env /user:Scripts cmd

to open a command prompt window with the task account. From that command prompt, I try again the "powershell .\script.ps1" and this time, it doesn't wait. It runs the command and moves on immediately before the command is finished. So I thought it might be an issue with the "Scripts" account, until I opened a new command prompt with runas Administrator

runas /env /user:Administrator cmd

When I call the script from this Administrator command prompt, the -Wait switch is also ignored, and the script moves along immediately after calling it without waiting for it to finish.

The odd part about this is that when I call it from the command prompt from Administrator account without doing runas, it works. Same account, two different results. Any ideas as to what the hell is going on here, and equally importantly, how to fix it?

OS is Server 2008 R2, running powershell 3.0

Answer

mjolinor picture mjolinor · Dec 26, 2013

Can't tell you why it's doing it, but I think this might work around it:

$proc = Start-Process -FilePath "C:\Pfx Engagement\Admin\Utilities\Backup Restore\BackupRestoreUtil.exe" -ArgumentList "/f "$backup_directory"" -Passthru
do {start-sleep -Milliseconds 500}
until ($proc.HasExited)

The -Passthru switch will make it return a Process object for the process, and you can test that to see when the process has exited.