Using the snippet below, I'm trying to find a way to suppress the "Attempted to divide by zero" error, and be left with just the custom error message in $err. I've tried combinations of try/catch, Invoke-Command/Expression, redirecting 2>$null, but in every case the error stream still contains the "attempted to divide by zero" message.
function func1 {
[CmdletBinding()]
param()
func2 -ErrorAction SilentlyContinue -ErrorVariable er
if ($er.Count -ge 1) {
Write-Error -Message "Custom error message!"
}
}
function func2 {
[CmdletBinding()]
param()
1/0
}
func1 -ErrorAction SilentlyContinue -ErrorVariable err
$err
populates $err with two items:
Attempted to divide by zero.
At line:15 char:3
+ 1/0
+ ~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
func1 : Custom error message!
At line:18 char:1
+ func1 -ErrorAction SilentlyContinue -ErrorVariable err
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,func1
Thanks so much for your thoughts!