# Try/catch in for each loop with invoke-command

**URL:** <https://forums.powershell.org/t/try-catch-in-for-each-loop-with-invoke-command/18170>\
**Category:** PowerShell Help\
**Created:** [December 16, 2021, 3:12pm UTC](https://forums.powershell.org/t/try-catch-in-for-each-loop-with-invoke-command/18170 "2021-12-16T15:12:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![adrimus](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/adrimus/32/4925_2.png) [@adrimus](https://forums.powershell.org/u/adrimus)\
**Post date:** [December 16, 2021, 3:12pm UTC](https://forums.powershell.org/t/try-catch-in-for-each-loop-with-invoke-command/18170/1 "2021-12-16T15:12:59Z")

</div>

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

```auto
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
    }
    
}

```

---

<div class="post-metadata">

**Author:** ![krzydoug](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/krzydoug/32/1008_2.png) [@krzydoug](https://forums.powershell.org/u/krzydoug)\
**Post date:** [December 16, 2021, 3:24pm UTC](https://forums.powershell.org/t/try-catch-in-for-each-loop-with-invoke-command/18170/2 "2021-12-16T15:24:10Z")

</div>

Remove return. Return ends the the current scope

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:19pm UTC](https://forums.powershell.org/t/try-catch-in-for-each-loop-with-invoke-command/18170/3 "2024-05-16T20:19:59Z")

</div>

Closed on May 16, 2024, 8:19pm UTC


