Invoke-Command As Job hangs due to one Server in Hung State

I am running the below code. When I do a get-job | wait-job | receive-job; The script never completes as one of the Computers in variable $mm_final is hung. Can you please advise how can I skip that “bad” server and complete the job and get results.

icm -jobname myjob -computername $mm_final -credential $cred {
        $t = gwmi -cl win32_terminalservice 
        $os = gwmi -cl win32_operatingsystem
         $uptime1 = [datetime]::now - $os.ConvertToDateTime($os.LastBootUpTime)
         $sessions = (quser) -replace "\s{2,}","," | ConvertFrom-Csv
         $icaSessions = $sessions | ? {$_.sessionname -match "ica"} | measure
         $vdisk = gp -path "HKLM:\system\CurrentControlSet\services\bnistack\PvsAgent"
         $ht.ICACount = $icasessions.count
         $ht.vdisk = $vdisk.diskname
         $ht.uptime="$($uptime1.days)d $($uptime1.hours)h $($uptime1.minutes)m"
         $temp1 = new-object -type psobject -prop $ht
         $temp1 | select serverName,vdisk,ICACount,uptime
		} -asjob 

You should test if the remote device is available before trying to run a script/command against it.

 if (Test-Connection -ComputerName $Computer){
          # Your code

Or test that you can enter a PSSession:

$Session = New-PSSession $ComputerName -Credential $Creds
  if ($Session){
  # Your code
#Sets up multiple CIM sessions
$computername = "Computer1", "Computer2"
$option = New-CimSessionOption -Protocol Dcom
$session = New-CimSession -ComputerName $computername -SessionOption $option

#runs only to connected sessions
$t = Get-CimInstance -CimSession $session -ClassName Win32_terminalservice
$os = Get-CimInstance -CimSession $session -ClassName win32_operatingsystem

Sessions will not be made with a system PowerShell cannot connect to. You can add erroraction and errorvariable to the New-CIMSession to trap any systems you cannot connect. The $option (protocol Dcom) allows a connection to a system without the most current PowerShell installed.

Script will collect the WMI data for each session consecutively. MUCH quicker than running Get-WMIObject against each system. In my opinion this is easier than working with jobs if you are only collecting WMI data.

Clean up your sessions with

Get-CIMSession | Remove-CIMSession

Hope this helps.

Good Luck!