i have the following code:
function Test-PendingReboot {
try {
$util = [wmiclass]'\.\root\ccm\clientsdk:CCM_ClientUtilities'
$status = $util.DetermineIfRebootPending()
if (($null -ne $status) -and $status.RebootPending) {
return $true
}
} catch {}
return $false
}
which is part of a function that, as you can see, checks if a system reboot is pending.
That casting to [wmiclass]
is possible only when a reboot is pending.
The function works correctly, but with the side effect of the casting error (when a reboot is not pending) going into the $Error
automatic variable. You can check with:
$error.clear()
Test-PendingReboot
$error
This will print the following (False
is just the return value of the call):
False
Cannot convert value "\.\root\ccm\clientsdk:CCM_ClientUtilities" to type "System.Management.ManagementClass". Error: "Invalid parameter "
At C:\_\t.ps1:26 char:89
+ … re'; return ([wmiclass]'\.\root\ccm\clientsdk:CCM_ClientUtilities') } …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastToWMIClass
I don't want that.
I want to have complete control over the error, as the error itself is also part of the logic of the function (because it means that a reboot is certainly not pending).
I want to control it as when using -ErrorAction ignore
instead of silentlycontinue
with a cmdlet.
I tried using the following:
$ErrorActionPreference = 'ignore'
$util = [wmiclass]'\.\root\ccm\clientsdk:CCM_ClientUtilities'
or even the following (yes that's mad):
$ErrorActionPreference = 'ignore'
$util = Invoke-Command -ScriptBlock { $ErrorActionPreference = 'ignore'; return ([wmiclass]'\.\root\ccm\clientsdk:CCM_ClientUtilities') } -ea Ignore
but nothing works...
I'm starting to doubt, Is it even possible?
PLEASE NOTE: this piece of code is just an example, my question is, in general, how to stop casting error from getting into $Error
?
thanks