Start-Job using variables

Easy one for some gurus.

I’m trying to replace an existing Windows script with a powershell equivalent to run across multiple files and folders and execute scripts with sequencing rules. The recursion of directories, and sequencing is all working and now I just want to execute the jobs, detect when completed, ideally detect errors to abort the process, and log the output to a common log file.

If I just start a process, it runs fine. But if I start a job using a variable, then:

  1. The job is listed as "$TheJob" from Get-Job
  2. I don't get any output from Receive-Job.
Start-Job -ScriptBlock {D:\MyWork\Powershell\10-Setup\20-LoadControlData\10-LoadControlData5.ps1}
$TheJob = "D:\MyWork\Powershell\10-Setup\20-LoadControlData\10-LoadControlData5.ps1"
Start-Job -ScriptBlock { $TheJob } 
get-job | Wait-Job
get-job | Receive-Job
See below, Hello World is output only once.
Id Name  PSJobTypeName State     HasMoreData  Location   Command 
-- ----  ------------- -----     -----------  --------   ------- 
62 Job62 BackgroundJob Running   True         localhost   D:\MyWork\Powershell\1...
64 Job64 BackgroundJob Running   True         localhost    $TheJob 
62 Job62 BackgroundJob Completed True         localhost   D:\MyWork\Powershell\1...
64 Job64 BackgroundJob Completed True         localhost    $TheJob 
Hello world!

The $TheJob variable is defined in a global scope which the ScripBlock doesn’t know about. It will never get the variable outside the job till you explicitly pass it to the scriptblock. You have to use Param() blocks in side the script block to use pass variables.

Start-Job -ScriptBlock {
    Write-Output -InputObject "Value of variable Param is $Param"

} -ArgumentList 'ValueForParam'

But here you don’t need to use ScriptBlock, Start-Job has a parameter named FilePath which will accept the path of the script run in backgroound.

Start-Job -FilePath $TheJob

You can even pass values to the $TheJob script using -ArgumentList if the script accepts parameter.

Please read the help documentation for more usages.

Get-Help Start-Job -Online

Excellent. Funny how when you are learning a new language and hit a problem and spiral on down a rabbit hole. This is solution is where I started many hours before. Thanks for the help.