简体   繁体   中英

How can I pass a variable to Start-Job command

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?

您需要在此处修复的2件事:使用using:前缀从调用范围中解析$command的值,然后使用& call运算符实际将$command作为命令调用:

Start-Job -ScriptBlock {& $using:command}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM