Here's my PowerShell 5.1 script to get service status on all machines. I'm giving each server 5 seconds to respond before moving on. However, it still looks like I'm getting the uncaught messages in addition to the friendly message I gave it. Any thoughts?
$results = @()
foreach ($server in $servers) {
try {
$job = Invoke-Command -ComputerName $server -Credential $Credential -ScriptBlock {
Get-Service -Name Bits
} -AsJob
if (Wait-Job -Job $job -Timeout $timeout) {
$result = Receive-Job -Job $job
$results += $result
} else {
Write-Output "Timeout: $server did not respond in $timeout seconds."
}
} catch {
Write-Output "Error: $_"
} finally {
Remove-Job -Job $job
}
}
$results
Your un-caught exception is coming from the finally block where you try to remove the job. This happens regardless of the success in your try block.