Powershell - Start-Job - Pass a variable based command

Paul Wasserman :

I'm trying to start a command within a script block, but this doesn't work. Is there an additional option required to make this work?

Code

$cmd = "dir c:\"
start-job -ScriptBlock {$cmd} -Name "Test1" 
Get-Job -Name "Test1" | Receive-Job -Keep

Output

PS C:\> $cmd = "dir c:\"

PS C:\> start-job -ScriptBlock {$cmd} -Name "Test1" 

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
41     Test1           BackgroundJob   Running       True            localhost            $cmd                     

PS C:\> Get-Job -Name "Test1" | Receive-Job -Keep
PS C:\> 
Wasif Hasan :

You have to execute the command inside $cmd with Invoke-Expression:

$cmd = "dir c:\"
$job = start-job -ScriptBlock {Invoke-Expression $cmd} -Name "Test1" 
$job | Wait-Job | Receive-Job 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390700&siteId=1