powershellstart-job

Powershell - Start-Job - Pass a variable based command


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:\> 

Solution

  • 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