Search code examples
powershelljobs

Powershell - scriptblock global variable


In powershell, Im trying to update the global variable from within the script block it doesnt seem to work, it always prints out the initial value

$globalVariable = "Initial Value"

# Start a background job with a script block
$job = Start-Job -ScriptBlock {
    $Global:globalVariable  = "New Value"
}

Wait-Job $job
$jobResult = Receive-Job $job
Write-Host "Global Variable Value: $Global:globalVariable "
Remove-Job $job

Solution

  • You cannot access external variables with Start-Job.
    The only workaround that I know is using Environment Variables ($env:*)

    [System.Environment]::SetEnvironmentVariable('TestVariable', 'OldVar', 'User')
    Write-Host "Global Variable Value BEFORE: $([System.Environment]::getEnvironmentVariable('TestVariable','User')) "
    
    
    $job = Start-Job -ScriptBlock {
        [System.Environment]::SetEnvironmentVariable('TestVariable', 'NewVar', 'User')
            
    } 
    Wait-Job $job
    Receive-Job $job
    Remove-Job $job
    
    Write-Host "Global Variable Value AFTER: $([System.Environment]::getEnvironmentVariable('TestVariable','User')) "
    
    # Necessary manual removal
    [System.Environment]::SetEnvironmentVariable('TestVariable', $null, 'User')