0

I am trying to write a load balanced powershell publishing script and have seem to hit a roadblock. The foreach loop below will spin up a process to deploy using MSDeploy given the arguments.

foreach ($server in $ServersToDeploy) {
    # Spin up a new process
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = $MSDeploy
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = $arguments
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    $p.WaitForExit()
    $stdout = $p.StandardOutput.ReadToEnd()
    $stderr = $p.StandardError.ReadToEnd()

    # Output
    if ($stderr) {
        throw $stderr + ("Exit Code: " + $p.ExitCode)
    }
    Write-Host $stdout
}

On the first run, it will run the script and execute MSDeploy with the proper arguments, but powershell would indefinitely wait for the first process to exit, but the publish seems to have executed successfully for both servers because when I re-run the command, the process executes quickly and properly for both servers with no changes.

This makes me think that this might be a timing issue, because when the publish goes through fast, it seems to work but when it's slow, it hangs on the first iteration of the publish.

1
  • You have possible deadlock here: $p.WaitForExit(); $stdout = $p.StandardOutput.ReadToEnd(); $stderr = $p.StandardError.ReadToEnd(). Commented Apr 25, 2016 at 22:25

1 Answer 1

2

Move the ReadToEnd calls above the WaitForExit

...
$p.Start() | Out-Null
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
$p.WaitForExit()
...
Sign up to request clarification or add additional context in comments.

1 Comment

You still have possibility for deadlock. You can stuck at reading StandardOutput but process can stuck at writing in StandardError.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.