Link to home
Start Free TrialLog in
Avatar of johnj_01201
johnj_01201

asked on

powershell 3+ try\catch error message output???

This code works, but no matter what I try I cannot get $error or $erroroutput to show the error messages. I can type them manually in the console\output sections of the PS IDE when the program stops to see what the errors are.
Any ideas?
Try
{
$CountCSV = Invoke-Sqlcmd -Query $Query -Username "test" -Password "test" -ErrorAction Stop -QueryTimeout 65535  
}
catch{
    $errorout += $error[0]
#This next line outputs the text in the quotes, but I cannot get it to do anything else
    Write-Error "CountCSV major error, query failed problem"
#this next line only shows the text in the quotes:
    Write-Error "CountCSV major error, query failed problem" $errorout
#nothing here shows up at all
            write-host $errorout
$error
$errorout
}

Again, I can type $error to see an error message and $errorout to see another error message. One is generic and the other is detailed. For example if there's a query time-out, one will basically say there's a networking issue while the other actual tells the query exceeded the timeout period. I would like to shows these 2 outputs automatically instead of having to type them to see what went wrong.
From what I've read on the Internet it should be working as expected, but it is acting like $error and $errorout are empty in the above example.

I've also used the same Try\Catch code in several invoke-sql sections of the program and none of them display the desired information.
SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of johnj_01201
johnj_01201

ASKER

Thanks. I guess the try\catch is not as simple as I thought. I will research and learn more about it.
Proper error handling is indeed a more advanced topic ...
I can't remember where I've read it, but I believe I've seen it said a few times that error handling can easily double the size of your script, and take twice as long to write as the main script portion (or more).