Powershell - Start-Job - 传递基于变量的命令
Powershell - Start-Job - Pass a variable based command
我试图在脚本块中启动命令,但这不起作用。是否需要其他选项才能完成这项工作?
代码
$cmd = "dir c:\"
start-job -ScriptBlock {$cmd} -Name "Test1"
Get-Job -Name "Test1" | Receive-Job -Keep
输出
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:\>
您必须使用 Invoke-Expression 在 $cmd 中执行命令:
$cmd = "dir c:\"
$job = start-job -ScriptBlock {Invoke-Expression $cmd} -Name "Test1"
$job | Wait-Job | Receive-Job
能够使它正常工作...需要添加参数。感谢您的帮助。
$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...
我试图在脚本块中启动命令,但这不起作用。是否需要其他选项才能完成这项工作?
代码
$cmd = "dir c:\"
start-job -ScriptBlock {$cmd} -Name "Test1"
Get-Job -Name "Test1" | Receive-Job -Keep
输出
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:\>
您必须使用 Invoke-Expression 在 $cmd 中执行命令:
$cmd = "dir c:\"
$job = start-job -ScriptBlock {Invoke-Expression $cmd} -Name "Test1"
$job | Wait-Job | Receive-Job
能够使它正常工作...需要添加参数。感谢您的帮助。
$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...