0

Null Output

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:

enter image description here

5
  • what is $DeviceStatus.Powerstate.gettype() ? Commented Jan 22, 2021 at 16:25
  • @T-Me Int64 - this is partially why my mind was blown when this didn't work. I had checked the type beforehand and was like yep... Int64 should definitely work. Commented Jan 22, 2021 at 16:30
  • 2
    The hash table keys are Int32 type. You need to cast to Int32 first -> $PowerStateMap[[int]$DeviceStatus.PowerState] Commented Jan 22, 2021 at 16:32
  • 2
    Hashtable is not generic; it uses object keys. Unfortunately the .NET equality rules make it so that a boxed Int64 is not ever considered identical to a boxed Int32, no matter their values. This is a leaky abstraction; PowerShell doesn't really "do" anything with boxing, but it suffers the consequences anyway. Commented Jan 22, 2021 at 16:33
  • Why not upload images of code/errors when asking a question? Commented Jan 22, 2021 at 18:03

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.