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

1

13

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

Abolish answered 26/12, 2013 at 20:22 Comment(1)
After upgrading PS 2 to 3 I stumbled upon the same problem. -Wait worked perfectly fine in PS version 2! Workaround with waiting till the process finishes has one huge issue - it doesn't return the .ExitCode of the processEnjoin
P
12

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.

Peterus answered 26/12, 2013 at 20:39 Comment(2)
There is a problem with this approach - $proc.ExitCode is unavailableEnjoin
And by the way - instead of start-sleep-ing you can just use $proc.WaitForExit(). It still doesn't set $proc.ExitCode though ))Enjoin

© 2022 - 2024 — McMap. All rights reserved.