Passing parameters to a Powershell Job using scriptblock

53 views Asked by At

When I use this script works fine

$job = start-job -ScriptBlock {param($name);Write-Host $name} -ArgumentList "Test" 
Receive-Job -Job $job

But when I do this does not works

$scriptblock = {param($name);Write-Host $name}
$job = start-job -ScriptBlock {$scriptblock} -ArgumentList "Test" 
Receive-Job -Job $job

Can you help me?

Thanks

1

There are 1 answers

0
Santiago Squarzon On

Second example is calling a variable $scriptblock that is not defined in the job scope if you want to pass in that variable as argument of -ScriptBlock parameter then you need to remove the curly braces:

$scriptblock = { param($name); Write-Host $name }
$job = Start-Job -ScriptBlock $scriptblock -ArgumentList 'Test'
Receive-Job -Job $job -AutoRemoveJob -Wait # Outputs: `Test`