Search code examples
powershelltry-catchinvoke-command

Try, catch in powershell invoke-command


It is not going to "catch" block as part of invoke-command for the incorrect host using powershell

$server= @("correcthost","Incorrecthost")
foreach($server in $server)
   {

     Try{
          Invoke-Command -ComputerName $server -ArgumentList $server -ScriptBlock    {

             $serverk=$args[0]    
             write-host $serverk
            }
        }
    Catch
       {
        write-host "error connecting to $serverk"
       }
  }

I expect the catchblock getting executed as i am trying to incorrect host

but the actual output is not printing catch block


Solution

  • There are two issues. First, the variable $serverk is out of scope in the catch block. It's being used only on the remote computer, so it doesn't exist - or have value - on the local system.

    Debugging any Powershell script should always start with turning on the strict mode, so warnings about uninitialized variables are generated. Like so,

    Set-StrictMode -Version 'latest'
    ...<code>
    The variable '$serverk' cannot be retrieved because it has not been set.
    At line:12 char:41
    +         write-host "error connecting to $serverk"
    +                                         ~~~~~~~~
        + CategoryInfo          : InvalidOperation: (serverk:String) [], RuntimeException
        + FullyQualifiedErrorId : VariableIsUndefined
    

    The fix is easy, just refer to $server that's the variable used in iterating $servers.

    The second issue is caused by ErrorAction, or to be specific, not declaring one. Add -ErrorAction Stop to Invoke-Command and process the exception in catch block like so,

    catch{
        write-host "error connecting to $server`: $_"
    }
    error connecting to doesnotexist: [doesnotexist] Connecting to remote server doesnotexist failed...