0

I'm trying to run two Invoke-Sqlcmd in parallel and then wait all the results.

$server1 = '...'
$server2 = '...'

workflow work {
  parallel {
    $r1 = Invoke-Sqlcmd -ServerInstance $server1 'select 1 a'
    $r2 = Invoke-Sqlcmd -ServerInstance $server2 'select 2 a'
  }
}
work
# do something with $r1 and $r2. How to access the variables here?
  1. How to pass $server1 and $server2 to the code block?
  2. How to get $r1 and $r2 from the parallel block?
4
  • Given that workflows are obsolescent (they're no longer supported in PowerShell Core), I suggest looking into Start-ThreadJob - see this answer. Commented Oct 28, 2019 at 23:00
  • You can pass in servers with a param (). Not sure how to get the results except $result = work $server1 $server2. Maybe jobs is easier. Commented Oct 29, 2019 at 2:17
  • 1
    @mklement0, I tried ThreadJob. But it doesn't work with Invoke-SqlCmd stackoverflow.com/questions/58609740/… Commented Oct 29, 2019 at 14:47
  • Interesting, @ca9163d9: I think the problem is a bug in Invoke-SqlCmd, as detailed in my comment on your linked question. You can work around the problem with regular child-process-based background jobs (Start-Job), but note that they have a lot more overhead than thread jobs - for long-running SQL queries that won't matter, however. Commented Oct 29, 2019 at 19:48

1 Answer 1

1

So pass in servers with param, and return a hashtable of both results.

$server1 = '...'
$server2 = '...'

workflow work {
  param ($server1, $server2)
  parallel {
    @{r1 = Invoke-Sqlcmd -ServerInstance $server1 'select 1 a'}
    @{r2 = Invoke-Sqlcmd -ServerInstance $server2 'select 2 a'}
  }
}
$r = work $server1 $server2
$r.r1
$r.r2
Sign up to request clarification or add additional context in comments.

2 Comments

It works. However, I will use Start-ThreadJob as @mklement0 mentioned that workflow is obsolescent in the comment.
I'm not sure if it's still parallel.

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.