title: Powershell error handling using invoke-command calling .bat file
body: <p>I'm trying to use a TRY-CATCH block to capture the error of an invoke-command I'm using to call a remote .bat file on another server. </p>
  
  <p>If the .bat file fails (it's executing a SP on the local SQL server to run a backup), I would like Powershell to know the .bat file had an error and go into my CATCH block.</p>
  
  <p>However, if the .bat file fails, it doesn't catch the error. If the call to the .bat file fails (because I purpose renamed it to something that doesn't exist), it still does not go into my CATCH block.</p>
  
  <p>What am I missing?</p>
  
  <pre><code>$scriptblock = {\\RemoteServerA\run.bat}
     try
     {
        Invoke-command –ComputerName $TargetComp -ScriptBlock $scriptblock -Credential $cred
     }
     catch
     {
        send-mailMessage -to "me@mail.ca" -subject "Remote .bat file failed" -from "you@mail.ca" -body ".bat file failed" -SmtpServer "smtp.me.ca" -credential $cred
     }
  </code></pre>
  
  <p>I even tried it using an <code>if</code>...<code>else</code> block, and by this way it was a bit better. It would fail if the call to the .bat file failed because I renamed it to something that doesn't exist. However if the contents of the .bat file failed (i.e. the SP failed), it would not recognize that failure, but seem like it sees the call to the .bat file was successful, and not fail.</p>
  
  <p>This was a more complete set of code, since my goal is to execute a 2nd batch file on the remote server upon successful completion of the first batch file on the remote server.</p>
  
  <pre><code>Invoke-command –ComputerName $TargetComp –ScriptBlock $scriptblock -Credential $cred
  
  if ($? -eq "True")
     {Invoke-command –ComputerName $TargetComp –ScriptBlock $scriptblock2 –credential $cred
     $output2 = $?
  
     if ($output2 -eq "True")
        {send-mailMessage -to "me@mail.ca" -subject "Backup Successful" -from "me@mail.ca" -body "Yippee" -SmtpServer "smtp.me" -credential $cred
        Write-Host "Backup Successful"
        }
     else {send-mailMessage -to "me@mail.ca" -subject "BackupDB failed" -from "me@mail.ca" -body "BackupDB failed" -SmtpServer "smtp.me" -credential $cred
        Write-Host "Backup Failed" + $output2
        }
     }
  else {send-mailMessage -to "me@mail.ca" -subject "DatabaseCheckDB failed" -from "me@mail.ca" -body "DatabaseCheckDB failed" -SmtpServer "smtp.me" -credential $cred}
  </code></pre>