0

I'm trying to catch errors inside a invoke-command loop. I want to catch, write an error of my own and then continue my loop but I keep getting the exception printed out and my catch does nothing. The example below is what I'd like to work.

$Result = Invoke-Command -Computer $computer -ScriptBlock {

            $instanceName = "MSSQL`$SQLEXPRESS"

            try {

                $sqlService = Get-Service -Name $instanceName

            } catch {

                Write-Host "No SQL on server $env:COMPUTERNAME"
                return $_
                continue
            }

Patrik Persson
  • 173
  • 1
  • 2
  • 15
  • The [linked duplicate](https://stackoverflow.com/a/59641995/45375) has background information on error types in PowerShell. – mklement0 Mar 10 '20 at 13:43

1 Answers1

3

Not finding the named service is not considered critical - it is a "non-terminating" error. You still get an error message/object, but it's (by design) not enough to invoke the catch. You can force it (i.e. make it "terminating") using the ErrorAction parameter, like this:

$sqlService = Get-Service -Name $instanceName -ErrorAction Stop

boxdog
  • 7,894
  • 2
  • 18
  • 27