本文介绍了如何测试(可能的)未知类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

$PSVersionTable.PSVersion -is [semver]

但是如果您在脚本中实现它并在 Windows PowerShell 环境,会报错:

无法找到类型 [semver].在行:1 字符:31+ $PSVersionTable.PSVersion -is [semver]+ ~~~~~~~~+ CategoryInfo : InvalidOperation: (semver:TypeName) [], RuntimeException+ FullQualifiedErrorId : TypeNotFound

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

$PSVersionTable.PSVersion -is `semver`
无法将System.String"类型的semver"值转换为System.Type"类型.在行:1 字符:1+ $PSVersionTable.PSVersion -is 'semver'+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : NotSpecified: (:) [], RuntimeException+ FullQualifiedErrorId:运行时异常

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

解决方案

感谢 vexx32 对于这个答案:

'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 .

To test for this specific type in the PowerShell Core environment, you would probably use the syntax:

$PSVersionTable.PSVersion -is [semver]

But if you implement this in a script and run this in the Windows PowerShell environment, you will get an error:

A similar error appears when I compare it to a type name (string):

$PSVersionTable.PSVersion -is `semver`

What is the best way to test for a type and prevent any error if the type is unknown (as happens with the -is operator for certain types in a specific environment)?

解决方案

Thanks to vexx32 for this answer:

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

E.g.:

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

这篇关于如何测试(可能的)未知类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:46