What is the best way to detect if an error occurs in a script function? I'm looking for a consistent way to indicate error/success status similar to $? (which only works on cmdlets, not script functions).
Given a particular function might return a value to be used by the caller, we can't indicate success by returning a boolean. A function could use a [ref] parameter and set the value appropriately inside the function and check after the call, but this is more overhead than I'd like. Is there something built-in to PowerShell that we can use?
The best I can come up with is:
- In the function use Write-Error to put ErrorRecord objects in the error stream;
- call the function with an ErrorVariable parameter;
- check if the ErrorVariable parameter is not null after the call.
For example:
function MyFun {
[CmdletBinding()] # must be an advanced function or this
param () # will not work as ErrorVariable will not exist
process {
# code here....
if ($SomeErrorCondition) {
Write-Error -Message "Error occurred; details..."
return
}
# more code here....
}
}
# call the function
$Err = $null
MyFun -ErrorVariable Err
# this check would be similar to checking if $? -eq $false
if ($Err -ne $null) {
"An error was detected"
# handle error, log/email contents of $Err, etc.
}
Is there something better? Is there a way of using $? in our script functions? I'd rather not throw exceptions or ErrorRecord objects and have tons of try/catch blocks all over the place. I'd also rather not use $Error as would require checking the count before making the function call as there could be other errors in there before the call - and I don't want to Clear() and lose them.
try/catch
? It doesn't add much more than theif
statement does;try{}catch{}
vs.if($err){}
is only a 2 char difference. – Rynantfoo -ev Err
if ($? -eq $false) { ReportError $Err }
Wrapping every function call in try/catch is distracting to me; following every function call with aif (...) { ReportError ... }
seems cleaner. I would prefer to only wrap code in try/catch if I really can't catch/prevent a terminating error otherwise. – DanWdir nodrivefound:\
ErrorRecords are put in the error stream and can be captured with 2> or -ErrorVariable, $? is $false so the error is easily detected but the script doesn't terminate and there's no try/catch. I was hoping for something like that. – DanW