finding index of key in an ordered dictionary in powershell

Question:

I am having a little bit of trouble with hashtables/dictionaries in powershell. The most recent roadblock is the ability to find the index of a key in an ordered dictionary.

  • I am looking for a solution that isn’t simply iterating through the object.
    (I already know how to do that)

Consider the following example:

If this were a normal array I’d be able to look up the index of an entry by using IndexOf().

That would return 2 under normal circumstances.

If I try that with an ordered dictionary, though, I get -1.

Any solutions?


Edit:
In case anyone reading over this is wondering what I’m talking about. What I was trying to use this for was to create an object to normalize property entries in a way that also has a numerical order.

I was trying to use this for the status of a process, for example:

If you were able to easily do this, the above object would give $_processState.error an index value of 0 and ascend through each entry, finally giving $_processState.complete an index value of 5. Then if you compared two properties, by “index value”, you could see which one is further along by simple operators. For instance:

^^that doesn’t work as is, but that’s the idea. It’s what I was aiming for. Or maybe to find something like $_processState.complete.IndexNumber()

Having an object like this also lets you assign values by the index name, itself, while standardizing the options…

Not really sure this was the best approach at the time or if it still is the best approach with all the custom class options there are available in PS v5.

Answer:

It can be simpler

It may not be any more efficient than the answer from Frode F., but perhaps more concise (inline) would be simply putting the hash table’s keys collection in a sub expression ($()) then calling indexOf on the result.

For your hash table…

Your particular expression would be simply:

…which gives the value 2 as you expected. This also works just as well on a regular hashtable… unless the hashtable is modified in pretty much any way, of course… so it’s probably not very useful in that case.

In other words

Using this hash table (which also shows many of the ways to encode 4…):

would yield the following expression/results pairs:

by the way:

  • [int][char]'4' equals [int]52
  • [char]'4' has a “value” (magnitude?) of 52, but is a character, so it’s used as such

…gotta love the typing system, which, while flexible, can get really really bad at times, if you’re not careful.

Source:

finding index of key in an ordered dictionary in powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply