Search code examples
powershelljobs

How to add Parameters into a Job using argument list


I'm trying to create a responsive form, using jobs, and the Add-Jobtracker matrix. The problem that I have is when I try to call variables inside the job. I used the -Argumentlist parameter but it is always Null, and I'm sure that the way that I'm using it is wrong, could you please guide me with this?

This is just an example, as my original script is a little bit more complex, below script will only write text from 2 variables to a textbox. I've created the same outside and inside the jobscript, used argument list and param inside it and it didn't work.

$Var1 = "sdaasdsadsa"
$Var2 = "asdasdsadsadsa"

$JobScript = {
    Param($Var1, $Var2)
    Write-Host $Var1, $Var2
}

$UpdateScript = {
    Param($Job)
    $texbox.Text = 'Working...'
}

$CompletedScript = {
    Param($Job)
    $results = Receive-Job -Job $Job
    $textbox.Text = $results    
}

Add-JobTracker -Name "test" -JobScript $JobScript -UpdateScript $UpdateScript -CompletedScript $CompletedScript -ArgumentList $var1, $Var2

At this point it is not doing anything, I have an alternative code but it is longer than this one, and I did not want to bother you guys with a lot of lines.


Solution

  • The job is running under a different scope than the rest of your script, and in that scope the variables aren't defined and therefore $null. To call variables inside a job, use the $Using:Varname syntax. Eg:

    $Test = "TEST!"
    $null = Start-Job {
        $Test
    }
    $Job = Get-Job
    Start-Sleep -Seconds 2
    Receive-Job -Job $Job
    

    Yields no output at all, but:

    $Test = "TEST!"
    $null = Start-Job {
        $Using:Test
    }
    $Job = Get-Job
    Start-Sleep -Seconds 2
    Receive-Job -Job $Job
    

    Yields:

    TEST!
    

    Read more about Remote Variables here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-6