Reputation: 167
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:\>
Upvotes: 0
Views: 1134
Reputation: 21
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
Upvotes: 0
Reputation: 167
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...
Upvotes: 1
Reputation: 15528
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
Upvotes: 0