Feature Request: -Is operator: suppress "Cannot convert"error
See original GitHub issueSuppress the error on the -is
operator when the type is supplied as a string:
$a -is 'UndefinedType'
Cannot convert the "UndefinedType" value of type "System.String" to type "System.Type".
At line:1 char:1
+ $a -is 'UndefinedType'
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
If “strict” programming is required, the system.type (square brackets) should be used instead:
$a -is [UndefinedType]
Unable to find type [UndefinedType].
At line:1 char:8
+ $a -is [UndefinedType]
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (UndefinedType:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
(Were the error is actually generated by the type casting and not the -is
operator.)/sub>
This would allow for easier type checking on types that might not exist in certain environments (like [semver]
that doesn’t exist in Windows PowerShell, see also: Stackoverflow: How to test a (possible) unknown type?
Besides, I think this is more in line with the general PowerShell behavor set by the PowerShell team: “Type Conversion in PowerShell is, without question, one of the most useful ingredients in its “Magic Sauce” of administrator effectiveness.” and looking to other comparison operators, there aren’t many operators that can produce an error.
In other words, from my perspective:
$a -is 'UndefinedType'
should just return $False
without error and $a -isnot 'UndefinedType'
should just return $True
without error.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:13
@iRon7 Even in non-strict mode, PowerShell tries to error on impossible behaviour. For example
is an error (unlike say Javascript). Likewise
123 + "abc"
is an error.$x.nosuchmethod()
is an error.123/0
is an error.[type] 'nosuchtype'
is an error. As much as possible, we try to treat things that make no sense as errors. In particular, we wanted implicit (or explicit) type conversions to be rational so[int] "123"
works but[int] "abc"
.@SeeminglyScience
Agree 100%. Type names tend to be long so it’s easy to make a mistake.
Yeah, I think I can get behind this. Asking whether an object is of a nonexistent type should probably just return
$false
; it certainly still answers the query the operator is designed to address.FWIW, you can workaround this for the time being with a pattern like this:
Which isn’t ideal but it does avoid the issue in the meantime. 🙂