views:

34

answers:

1

I need to complete a series of tasks across several Windows 2008 servers that need elevated permissions and as such I've had to create a series of scheduled tasks that i'm running via psexec. Since they have to run in sequence, I found and modified a powershell script that 'stalls' until scheduled tasks are completed on remote machines. The problem I have is that when I launch the script with psexec on the remote machine, once it completes running (indicated by a message in the console output) PowerShell.exe doesn't exit cleanly, but rather hangs out and holds up the entire process. I need powershell to quit after the delay script exits, but even with an exit keyword at the end it stays in memory and prevents the process from finishing. I'm not terribly experienced with powershell so I'll attach my script in case I'm doing something foolish in it:

while($true) {
$status = schtasks /query /tn "AutoDeploy"| select-string -patt "AutoDeploy"
if($status.tostring().substring(64,7) -eq "Running") { "Waiting for task to complete..." } else { break }
start-sleep -s 5
}
"Task complete."
exit

Thanks in advance for any insight.

+1  A: 

This works for me (using a different task name) and doesn't hang psexec:

$taskName = "AutoDeploy"
while (1)
{
    $stat = schtasks /query /tn $taskName | 
                Select-String "$taskName.*?\s(\w+)\s*$" | 
                Foreach {$_.Matches[0].Groups[1].value}
    if ($stat -ne 'Running')
    {
        "Task completed"
        break
    }
    "Waiting for task to complete"
    Start-Sleep 5
}
Keith Hill
While this didn't correct my particular issue, it's a far more elegant solution and I implemented it in place of mine.
Max Pollack
I had some trouble running some PowerShell scripts over SSH, where PowerShell would hang after finishing the last command (but only with some scripts). I worked around the issue by hooking stdin of powershell.exe to nul. So something was waiting on stdin, but I don't know what.
JasonMArcher
Since the remote execution of powershell was all within the context of our network and I could query the status of the scheduled task remotely, I discovered running the script locally rather than via psexec resulted in much more consistent and reliable output. This worked better, so I guess psexec was expecting something.
Max Pollack