Sagor Sen Golder
Sagor Sen Golder

Reputation: 21

Return multiple values in PowerShell

Given the following Script, how can I return two variables to the main code?

I have tried the return command but show an error. Please find the code and error message below.

Code:

workflow Test-MultiReturnVals
{
  parallel
  {
    $a = @(Test-Connection 8.8.8.8 -count 3)  
    $b = @(Test-Connection 4.2.2.1 -count 3)
    return $a, $b
  }
}
$c, $d = Test-MultiReturnVals
$c

Error:

Microsoft.PowerShell.Utility\Write-Error : The workflow was terminated by a
Terminate activity.
At RunScripts:9 char:9
+
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WorkflowReturnException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Workflow.WorkflowReturnException,Microsoft.PowerShell.Commands.WriteErrorCommand
    + PSComputerName        : [localhost]

Upvotes: 1

Views: 2041

Answers (1)

You shouldn't have the return statement in the parallel block. By definition, statements in the parallel block are run concurrently so you return before the values are populated ("return" is a terminate activity). Take a look here: https://learn.microsoft.com/en-us/powershell/module/psworkflow/about/about_parallel

To make it work the way you want to, you need to define the variables before the parallel block, then reference those variables inside the parallel block, and finally return the variables at the end. Be aware that you need to use $WORKFLOW: to reference the variables inside the parallel block.

Upvotes: 1

Related Questions