如何测试(可能的)未知类型?
How to test a (possible) unknown type?
PowerShell Core appears to have semantic versioning which includes a new type accelerator called [semver]
and is based on the System.Management.Automation.SemanticVersion
class .
要在 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 区分提供 [=17=] 或 'String'
作为比较和仅提供 return [=19,则应该是 nice/correct =]如果字符串无法转换)
测试类型并在类型未知时防止任何错误的最佳方法是什么(就像特定环境中某些类型的 -is
运算符所发生的那样)?
目前我能想到的最佳答案是:
$Object.PSTypeNames -Contains '.NET Framework type'
例如:
$PSVersionTable.PSVersion.PSTypeNames -Contains 'System.Management.Automation.SemanticVersion'
但这将使 type accelerators 无法使用。
感谢 vexx32 的回答:
(另见:Feature Request: -Is operator: suppress "Cannot convert"error #10504)
'UnknownType' -as [type] -and $object -is [UnknownType]
例如:
'semver' -as [type] -and $PSVersionTable.PSVersion -is [semver]
PowerShell Core appears to have semantic versioning which includes a new type accelerator called [semver]
and is based on the System.Management.Automation.SemanticVersion
class .
要在 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 区分提供 [=17=] 或 'String'
作为比较和仅提供 return [=19,则应该是 nice/correct =]如果字符串无法转换)
测试类型并在类型未知时防止任何错误的最佳方法是什么(就像特定环境中某些类型的 -is
运算符所发生的那样)?
目前我能想到的最佳答案是:
$Object.PSTypeNames -Contains '.NET Framework type'
例如:
$PSVersionTable.PSVersion.PSTypeNames -Contains 'System.Management.Automation.SemanticVersion'
但这将使 type accelerators 无法使用。
感谢 vexx32 的回答:
(另见:Feature Request: -Is operator: suppress "Cannot convert"error #10504)
'UnknownType' -as [type] -and $object -is [UnknownType]
例如:
'semver' -as [type] -and $PSVersionTable.PSVersion -is [semver]