如何测试(可能的)未知类型?



PowerShell Core似乎具有语义版本控制,其中包括一个名为[semver]的新型加速器,并且基于System.Management.Automation.SemanticVersion类。

若要在 PowerShell 核心环境中测试此特定类型,可以使用以下语法:

$PSVersionTable.PSVersion -is [semver]

但是,如果您在脚本中实现并在Windows PowerShell环境中运行它,则会收到错误:

Unable to find type [semver].
At line:1 char:31
+ $PSVersionTable.PSVersion -is [semver]
+                               ~~~~~~~~
+ CategoryInfo          : InvalidOperation: (semver:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound

当我将其与类型名称(string(进行比较时,会出现类似的错误:

$PSVersionTable.PSVersion -is `semver`
Cannot convert the "semver" value of type "System.String" to type "System.Type".
At line:1 char:1
+ $PSVersionTable.PSVersion -is 'semver'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException

(如果PowerShell区分提供[Type]'String'作为比较,如果字符串无法转换,则返回$False,那就太好了/正确(

如果类型未知,测试类型并防止出现任何错误的最佳方法是什么(就像特定环境中某些类型的-is运算符一样(?

感谢vexx32提供此答案:
(另请参阅:功能请求:-is 运算符:抑制"无法转换"错误 #10504(

'UnknownType' -as [type] -and $object -is [UnknownType]

例如:

'semver' -as [type] -and $PSVersionTable.PSVersion -is [semver]

到目前为止,我能想到的最好的答案是:

$Object.PSTypeNames -Contains '.NET Framework type'

例如:

$PSVersionTable.PSVersion.PSTypeNames -Contains 'System.Management.Automation.SemanticVersion'

但这将使使用类型加速器变得不可能。

最新更新