Dyota's blog

PowerShell error handling the dumb way

try/catch blocks only catch terminating errors. It won't catch non-terminating errors (i.e. Invoke-SqlCmd output non-terminating errors, and will thus not work as expected).

$Error.Clear()

# do your commands here

if ($Error.Count -gt 0) {
    "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")  $view`: $($Error[0].Exception.Message)`n"  >> log.txt
}