Invoke-Command in a background job

落花浮王杯 提交于 2019-12-02 01:02:25

Looks like you should do it the other way:

http://technet.microsoft.com/en-us/library/hh849698.aspx

To run a background job on a remote computer, use the AsJob parameter that is available on many cmdlets, or use the Invoke-Command cmdlet to run a Start-Job command on the remote computer. For more information, see about_Remote_Jobs.

I prefer to use Start-Job to run invoke-command so that I can watch and handle the jobs on the central machine using Get-Job.

When I loop through the "list of remote computers" I use the "current computer name" as the -Name parameter in the Start-Job so that I can watch each job individually and as a group.

Just my two cents from experience.

Edit Example:

$job =
{ 
    $remoteJob = { ##Do Stuff Here }
    Invoke-Command -ComputerName $args[0] -ScriptBlock $remoteJob
}
Start-Job -Name <jobName> -ScriptBlock $job -ArgumentList <remoteComputer>

To your question about why the Job "never finishes" I don't have input other than, make sure the code you are running remotely does actually end.

Hope this helps

This will also work, at least in Powershell 5

invoke-command -asjob -computer $PC -scriptblock { ## do stuff }

For Latest version of PS you can create a New Session and use it with Invoke-Command start-job cmdlets instead of using the ComputerName arguments directly.

$s = new-pssession -computername Server01
invoke-command -session $s -scriptblock { start-job -scriptblock {get-eventlog system}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!