Search code examples
powershelltry-catchinvoke-command

How do I try/catch inside invoke-command and continue?


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
            }


Solution

  • 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