Monday, February 22, 2010

How to check for existing key in a hashtable in powershell?

You may need to check for the existence of an existing key or value for various purposes. Luckily Powershell hash table provides ready made methods which saves us a lot of pain of searching though the hash using a loop or some other construct.
To find if a key already exists use $hash.containsKey(key). Remember that if key is case insensitive if it happens to be a string. You can also use $hash.contains(key) mthod which is just a shortcut to containskey method.
Similarly to find a value already existing in the hash; use $hash.containsValue(value). Remember that values are case sensitive if they happens to a be a string.

How to Make a Hash Table in Powershell?

To intialize a blank Hash table use this syntax
$blankHash=@{}
some times we need to have a predefined hash value Initialized with key value pair. I those cases use this syntax.
$intializedHash=@{Key1=value1;key2=value2}
Please note that you need to put a semicolon as the separator between different values.
Add a key value pair to the hash table.