3

I have a powershell 2.0 script which should run a command on several servers and process the output. I want to run the command and the processing for each server in a background job.

The comand works without any problems and terminates within half a second or less:

Invoke-Command -ComputerName $client -ScriptBlock { #do some stuff }

But when I run this in a background job, the job doesn't terminate:

Start-Job { Invoke-Command -ComputerName $client -ScriptBlock { #do some stuff } }

Has someone a idea what the problem could be?

bones
  • 33
  • 1
  • 1
  • 5

4 Answers4

4

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.

Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
  • But this runs the job on the remote computer. I want to run the job on the executing computer and process the output from the invoke-command in this job. – bones Jul 17 '13 at 09:56
  • 1
    @bones I think the effect is the same. `Invoke-Command` should kick off the job on the remote machine and return immediately. You can use `Receive-Job -ComputerName` to get the result. – Andy Arismendi Jul 17 '13 at 10:00
2

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

1

This will also work, at least in Powershell 5

invoke-command -asjob -computer $PC -scriptblock { ## do stuff }
AndrewG
  • 36
  • 1
0

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}}
sriram26
  • 361
  • 3
  • 5