I'm a lazy programmer, and all this hash["Key"] punctuation is getting on my nerves. Is there a syntactic sugar (perhaps a different object type) that allows you to create hashtables that are accessed using member method syntax (hash.Key)? There are many easy hacks to do this in Ruby. Is there a hack to do this in Powershell?
Asked
Active
Viewed 862 times
1
-
It talking about Dictionary, etc, there may be useful information here: http://stackoverflow.com/questions/3577488/does-powershell-have-a-method-missing (I looked for "powershell method_missing", which is how Ruby ostruct and similar work.) – Jul 21 '12 at 17:39
1 Answers
4
Yes:
$hash = @{"a" = 1; "b" = 2 }
$val = $hash.a
NOTE: It's also something that works on any IDictionary, not just Hashtables.

Start-Automating
- 8,067
- 2
- 28
- 47

Lee
- 142,018
- 20
- 234
- 287
-
+1 because it does answer the question as presented. However, I wonder if there is similar support for common CLR types (such as Dictionary, or other indexable Collection, which might be returned from calling a method) .. – Jul 21 '12 at 17:42
-
1Damn, I'm stupid. I was failing, but because I trying to use it within string expansion, without using $(). I apologize for the inane question. I was referring to hashes @pst, not Dictionaries, though I appreciate your faith in my not asking a stupid question... I just failed by doing my first testing using bad syntax: "Expand ${hash.key}" rather than "Expand $($hash.key)". I hadn't tested it outside of string expansion. – Myrddin Emrys Jul 21 '12 at 18:18
-
Fun times... this works fine everywhere but where I was initially testing it. `$ExecutionContext.InvoteCommand.ExpandString('$($hash.key)')` fails. But the same command, passed '$($hash[''key'']' succeeds. – Myrddin Emrys Jul 23 '12 at 02:14