简体   繁体   中英

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

Was able to get this working... needed to add parameters. Thanks for your help.

$cmd = { param([string]$dirname) dir $dirname }
$job = start-job -ScriptBlock $cmd -Name "Test1" -ArgumentList "C:\"
$job | Wait-Job | Receive-Job -Keep
$job

PS C:\> $job | Wait-Job | Receive-Job -Keep

    Directory: C:\

Mode                LastWriteTime         Length Name                                                                                                                           
----                -------------         ------ ----                                                                                                                           
d-----       12/29/2019   9:46 AM                DevTools                                                                                                                       
d-----        5/29/2019   5:44 AM                ESD                                                                                                                            
d-r---         4/1/2020   3:11 AM                Program Files                                                                                                                  
...

PS C:\> $job
Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
77     Test1           BackgroundJob   Completed     True            localhost             param([string]$dirnam...

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 

You can use the using prefix to access the value within a scriptblock:

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

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