Home > front end >  Types in conditional always false
Types in conditional always false

Time:12-27

I am trying to pass an exception type to be ignored to a function, but also provide a default exception type to ignore. And that default is not working. So, given

function Test {
    param (
        [Type]$ExceptionType = [System.Management.Automation.ItemNotFoundException]
    )

    if ($ExceptionType -is [System.Management.Automation.ItemNotFoundException]) {
        Write-Host "Yes"
    } else {
        Write-Host "No: $ExceptionType"
    }
}

I would expect that running

Test

would return Yes because of the default value. But running

Test -ExceptionType:([System.Management.Automation.PSArgumentOutOfRangeException])

should return No: System.Management.Automation.PSArgumentOutOfRangeException, which is does.

The problem is somehow in the conditional, because

if ([System.Management.Automation.ItemNotFoundException] -is [System.Management.Automation.ItemNotFoundException]) {}

also returns false. But elsewhere, where $PSItem.Exception is the exception I am evaluating the ignore on,

if ($PSItem.Exception -is $waitOnExceptionType) {}

seems to work fine. So, what am I doing wrong, and why is the conditional not working in this case? I have also tried wrapping the type in ( ) as you have to do with the argument, as well as using a second variable for the conditional, like so

$defaultException = ([System.Management.Automation.ItemNotFoundException])
if ($ExceptionType -is $defaultException) {

But to no avail.

Hmm, I suspect I have bigger problems. Per @mathias-r-jessen I have revised to

if ($ExceptionType -eq ([System.Management.Automation.ItemNotFoundException])) {
    Write-Host "Yes"
} else {
    Write-Host "No: $($ExceptionType.GetType().FullName)"
}

And now the conditional works with the default, but when passing

Test -ExceptionType:([System.Management.Automation.PSArgumentOutOfRangeException])

I return No: System.RuntimeType rather than the correct type. So anything I do later that depends on the actual type is problematic.

CodePudding user response:

The -is operator is for testing whether a given value is an instance of a type.

To test whether a given type is a subclass of another, use the Type.IsSubclassOf() method:

$ignoredBaseType = [System.Management.Automation.ItemNotFoundException]

if($ExceptionType -eq $ignoredBaseType -or $ExceptionType.IsSubClassOf($ignoredBaseType)){
    # ignore ...
}
  • Related