0

I have an array of objects with a job saved in a variable. I loop through each object and try to use start job but I can't pass the variable.

My example:

$command = "whoami"
Start-Job -Name TESTJOB -ScriptBlock {$command}

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
16495  TESTJOB         BackgroundJob   Running       True            localhost            $command

As you can see the Command shows as $command and not whoami.

This means that I don't get the output I require.

I don't have to use Start-Job but I'm trying to get something like "threading" to work as some jobs in the array will take longer than others.

Can you suggest the best way to do this?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Dosk3n
  • 21
  • 2

1 Answers1

2

2 things you need to fix here: Use the using: prefix to resolve the value of $command from the calling scope and then use the & call operator to actually invoke $command as a command:

Start-Job -ScriptBlock {& $using:command}
mklement0
  • 382,024
  • 64
  • 607
  • 775
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 1
    More information on the `$using:` scope, including a PSv2 alternative, see https://stackoverflow.com/q/35492437/45375 – mklement0 Mar 17 '19 at 13:11