Variables in Start-Job do not get evaluated

powershell

Solution

Here is the solution. As Andy said, I needed to use $args array with the -ArgumentList parameter. This other thread was helpful: Powershell: passing parameters to a job

foreach($agent in $agentcomputers){
$agentslash = "\\"+$agent
$args = ($agentslash,"c:\grinder\examples\startAgent.cmd")
Write-Output 'Starting agent on '$agent

#psexc to start the agent
$ScriptBlock = {& 'psexec' @args } 

Start-Job -ScriptBlock $ScriptBlock -ArgumentList $args

}

Problem

My Powershell code doesn't evaluate the `$agent` variable: ``` foreach ($agent in $agentcomputers) { Write-Output 'Starting agent on '$agent # psexc to start the agent Start-Job -ScriptBlock {& psexec $agent c:\grinder\examples\startAgent.cmd} } ``` This link is similar to my problem, except I'm not calling an external Powershell script. I tried adding that in, using `$args[0]` for `$agent`, and adding the `-ArgumentList` parameters, but that didn't work. Edits/Replies `$agentcomputers` is just a list of computer names - each on its own line: ``` $agentcomputers = Get-Content c:\grinder-dist\agent-computers.txt ``` I have also tried this - and `$args[0]` doesn't evaluate: ``` Start-Job -ScriptBlock {& psexec $args[0] c:\grinder\examples\startAgent.cmd} -ArgumentList @($agent) ```

Original source

Related problems