Try/catch in for each loop with invoke-command

Hi All

Not sure why but when the invoke-command can’t connect to a computer in the loop and the error is thrown by the error action stop, the loop does not continue to the next one. I would have expected it to keep on looping.

$computers is a list of computer names

foreach ($computer in $computers) {
    try {
		Write-Verbose "connecting to $computer"
        Invoke-Command -ComputerName $computer -ScriptBlock ${Function:RemediateCVEIssue} -ErrorAction stop
    } catch {
        write-verbose "$computer is offline"

		$properties = @{
			ComputerName = $computer
			isDetected = ''
			path = ''
		}
		$obj = New-Object -Property $properties -TypeName psobject
		return $obj
        $computer | Out-File -FilePath "c:\logs\$timestamp-offline.txt" -Append
    }
    
}

Remove return. Return ends the the current scope

1 Like