Reputation: 1763
Based on the above example, why would the result of the above not be 'On'? I'm feeling rather foolish because this is so simple but in any other language $PowerStateMap[$DeviceStatus.PowerState]
would have returned 'On'. Does PowerShell have some weird trick for referencing a hashtable?
Update: I figured it out... I had to typecast $DeviceStatus.PowerState
to an int manually. Why did I have to do that?
Edit: For reference:
Upvotes: 0
Views: 952
Reputation: 25001
The problem is you are dealing with two different numeric types. The hash table contains keys of type Int32
. The referenced object contains Int64
values. The simple solution is to just cast the Int64
values as Int32
when a hash table value is retrieved.
$PowerStateMap[[int]$DeviceStatus.PowerState]
We can simulate the above with an example:
$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]
Output:
17
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int64 System.ValueType
"Testing Without Casting"
"Testing with casting"
On
Upvotes: 2