Andrew Ducker
Andrew Ducker

Reputation: 5520

Powershell hashtable keys property doesn't return the keys - it returns a KeyCollection object

If I create a hashtable, and then try to query it by key, it doesn't retrieve them. This is because the keys aren't actually the individual keys, they're instead something called a "KeyCollection". How do I get the actual key?

$states = @{1=2} #This creates the hashtable

$states.keys[0] #This returned 1

$States.get_item($states.keys[0]) # This returned nothing (expected 1)

$States.keys[0].getType() #This returned "KeyCollection" as the Name.

Can someone explain to me why it's "KeyCollection" and not 1, and how to get to the String?

Upvotes: 2

Views: 2252

Answers (2)

Mike Zboray
Mike Zboray

Reputation: 40838

I think what is going on is that KeyCollection doesn't have an indexer so PowerShell is interpreting the use of [0] as an attempt to access an item in an array and the KeyCollection is treated as a single item in an array.

You can loop over the keys with ForEach-Object:

$states.Keys | foreach { Write-Host "Key: $_, Value: $($states[$_])" }

Upvotes: 3

ojk
ojk

Reputation: 2542

Then you need to use get_enumerator, like so:

$states = @{"Alaska"="Big"}
$states.GetEnumerator() | ForEach-Object {
    Write-Host "Key: $($_.Key)"
    Write-Host "Value: $($states[$_.Key])"
}

Upvotes: 3

Related Questions