Hi,
In a script (in powershell 2.0) i use send-mailmessage cmdlet , and log errors in log file.
Smtp server, recipient, sender are parameters of my script.
I execute the cmdlet send-mailmessage using the -ErrorVariable MyError parameter.
Then i check the $? variable to see if any exception occured in the cmdlet execution. If so, i write information about the error in my log file, like this :
@"
Error on $($MyError[0].InvocationInfo.Mycommand.Name) :
Command line : $($MyError[0].invocationinfo.line)
Error message : $($MyError[0].Exception)
"@ | write-log MylogFile
(write-log is a own function using out-file with the parameters i need).
During my test, i found that most of the time it worked fine, but for some excetion, it doesn't. And my variable $MyError is not filled like the predefined powershell variable $Error.
For instance if your smtp server is down (or wrong name), it works.
If the -to parameter is not a valid email adress, it works.
But there are differences between how are filled the standard error variable and the one you specify in -ErrorVariable :
- if -to is empty or null, you don't get anything in $MyError variable. Yet, $Error[0] contains the information about the exception.
- if -from is not a valid email adress, $error[0] contains the information as usual, and $MyError too, but not in the same type :
$error[0].gettype().name returns ErrorRecord
$MyError[0].gettype().name returns CmdletInvocationException
If you want to access to exception information, you need to use $MyError[0].ErrorRecord instead of $MyError[0].
This is why $MyError[0].Exception (for instance) doesn't produce the expected result in my log file.
Do you know why it works that way ?
Is it the same for other cmdlets ?
Because if the result change depending on the exception, it's easier to use the predefined variable, and not to use -ErrorVariable parameter.
It's a bit confusing, isn't it ?