Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Catch with Invoke-SQLCmd and -ErrorAction SilentlyContinue

Tags:

powershell

Basically, I want to be able to catch the warnings returned from Invoke-SqlCmd without having to stop the script running. The following code does not work:

TRY {
    Invoke-SQLCMD -Query "selects * from syscomments" -ServerInstance $ServerAddress -Database $DatabaseName -ErrorAction 'SilentlyContinue' 
}
CATCH {
    Write-Host "[!] Errors returned, check log file for details" -ForegroundColor RED
    $_ | Out-File -Append "path to log"
}

This just suppresses all output and doesn't catch the error. Changing the error type to Stop does catch the error but I need these scripts to continue running after an error is hit.

like image 982
Owain Esau Avatar asked Aug 16 '26 00:08

Owain Esau


1 Answers

You can use a trap statement:

trap { # invoked on terminating errors
  Write-Host "[!] Errors returned, check log file for details" -ForegroundColor RED
  $_ | Out-File -Append "path to log" 
  continue # continue execution
}

# Elevate all non-terminating errors to (script-)terminating errors.
$ErrorActionPreference = 'Stop'

# All errors - whether non-terminating or terminating - now trigger
# the trap, which, due to use of `continue`, continues execution after each error.

Invoke-SQLCMD -Query "selects * from syscomments" -ServerInstance $ServerAddress -Database $DatabaseName  
like image 111
mklement0 Avatar answered Aug 18 '26 23:08

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!