基于上面的例子,为什么上面的结果不是'On'?我觉得很愚蠢,因为这很简单,但在任何其他语言中$PowerStateMap[$DeviceStatus.PowerState]
都会返回“开”。PowerShell 是否有一些奇怪的技巧来引用哈希表?
更新:我想通了...我必须$DeviceStatus.PowerState
手动将类型转换为 int 。为什么我必须这样做?
编辑:供参考:
基于上面的例子,为什么上面的结果不是'On'?我觉得很愚蠢,因为这很简单,但在任何其他语言中$PowerStateMap[$DeviceStatus.PowerState]
都会返回“开”。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