2

I'm trying to get the value of a variable modified inside a scriptblock:

function Test-Function {
    $var = "apple"
    Start-Job -ScriptBlock {
        $var = "banana"
    }
    Write-Host "Variable is $var"
}
Test-Function
Variable is: apple

I am trying to get the output 'banana'. Is this possible?

js2010
  • 23,033
  • 6
  • 64
  • 66
user9924807
  • 707
  • 5
  • 22
  • Possible duplicate of [Variable scoping in PowerShell](https://stackoverflow.com/questions/9325569/variable-scoping-in-powershell) – I.T Delinquent Sep 18 '19 at 09:58

1 Answers1

4

Since you are using PS Jobs in your code, you need to use wait for the job to get completed using wait-job and finally you have to receive the job using receive-job. Replace your code with the below:

function Test-Function {
    $var = "apple"
    Start-Job -ScriptBlock {
        $var = "banana"
        Write-Host "Variable is $var"
    } | Wait-Job -Any |Receive-Job

    #Write-Host "Variable is $var"
}
Test-Function

Hope it helps.

Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45