简体   繁体   中英

How do you pass a variable by reference within Start-Job?

How do you modify a variable within Start-Job ? This code outputs 0 , seemingly because the variable is passed by value:

$vara = "0"

$j = start-job -ScriptBlock {
   $args[0] = "1"
} -ArgumentList $vara

wait-job $j > $null
receive-job $j

Write-Host $vara  ## => "0"

How do you pass the parameter by reference (hence, outputting 1 )?

You're completely out of scope when modifying anything inside a job. Nothing will just magically populate in your current session.

You could do something like this:

$vara = "0"

$j = start-job -ScriptBlock {
   "1"
} -ArgumentList $vara

wait-job $j > $null
$vara = receive-job $j

Write-Host $vara

And if you need to populate a lot of arguments, you can do something like this:

$vara = "0"

$j = start-job -ScriptBlock {
   [pscustomobject]@{
      vara1 = "1"
      vara2 = "0"
    }
} -ArgumentList $vara

wait-job $j > $null
$vara = receive-job $j

Write-Host $vara.vara1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM