powershell - 如何测试(可能的)未知类型?
问题描述
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
特定环境中某些类型的运算符所发生的那样),测试类型并防止任何错误的最佳方法是什么?
解决方案
感谢vexx32的回答:(
另请参阅:功能请求:-Is 运算符:抑制“无法转换”错误 #10504)
'UnknownType' -as [type] -and $object -is [UnknownType]
例如:
'semver' -as [type] -and $PSVersionTable.PSVersion -is [semver]
推荐阅读
- java - Apache Kafka 交换内存使用情况
- php - 在 Woocommerce 中仅显示没有插件的最高运输类别成本
- java - Spring boot - Jackson 日期序列化和反序列化
- python-3.x - 想使用 selenium 和 python 下载数据
- objective-c - 如何在可可中获得所有可能的屏幕分辨率?
- html - 可访问性:是否推荐锚列表和一个段落中的选项卡索引?
- hive - Nifi PutHiveStreaming 将数据写入 HDFS 但无法查看 Hive 表中的数据
- ios - Crashlytics 是否会生成有关低内存应用程序终止 (iOS) 的崩溃报告?
- excel - VBA动态过滤excel列
- reactjs - React js,超过最大更新深度