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

北战南征 提交于 2019-12-19 05:47:25

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/20790798/start-process-wait-doesnt-work-when-script-is-launched-from-command-prompt-ope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!