首页 > 解决方案 > 如何测试(可能的)未知类型?

问题描述

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

要在 PowerShell Core 环境中测试此特定类型,您可能会使用以下语法:

$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 区分提供 a[Type]或 a'String'作为比较并$False在字符串无法转换时仅返回,那将是很好/正确的)

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

标签: powershelltypespowershell-core

解决方案


感谢vexx32的回答:(
另请参阅:功能请求:-Is 运算符:抑制“无法转换”错误 #10504

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

例如:

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

推荐阅读