如何解决PowerShell 哈希表引用返回 null
根据上面的例子,为什么上面的结果不是'On'?我觉得很愚蠢,因为这很简单,但在任何其他语言中,$PowerStateMap[$DeviceStatus.PowerState]
都会返回“On”。 PowerShell 是否有一些奇怪的技巧来引用哈希表?
更新:我想通了……我必须手动将 $DeviceStatus.PowerState
类型转换为 int。为什么我必须这样做?
编辑:供参考:
解决方法
问题是您正在处理两种不同的数字类型。哈希表包含 Int32
类型的键。引用的对象包含 Int64
值。简单的解决方案是在检索哈希表值时将 Int64
值转换为 Int32
。
$PowerStateMap[[int]$DeviceStatus.PowerState]
我们可以用一个例子来模拟上面的:
$PowerStateMap = @{
20 = 'Powering On'
18 = 'Off'
17 = 'On'
21 = 'Powering Off'
}
$DeviceStatus = [pscustomobject]@{PowerState = [int64]17}
$DeviceStatus.PowerState
$DeviceStatus.PowerState.GetType()
"Testing Without Casting"
$PowerStateMap[$DeviceStatus.PowerState]
"Testing with casting"
$PowerStateMap[[int]$DeviceStatus.PowerState]
输出:
17
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int64 System.ValueType
"Testing Without Casting"
"Testing with casting"
On
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。