PowerShell 哈希表引用返回 null

问题描述

Null Output

根据上面的例子,为什么上面的结果不是'On'?我觉得很愚蠢,因为这很简单,但在任何其他语言中,$PowerStateMap[$DeviceStatus.PowerState] 都会返回“On”。 PowerShell 是否有一些奇怪的技巧来引用哈希表?

更新:我想通了……我必须手动将 $DeviceStatus.PowerState 类型转换为 int。为什么我必须这样做?

编辑:供参考:

enter image description here

解决方法

问题是您正在处理两种不同的数字类型。哈希表包含 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