Friday, 29 March 2013

Hashtables in Powershell

Hashtables are good for creating dictionary-like data structures in Powershell, for look-ups and related functionality. The following powershell script code shows how to create a Hashtable in Powershell and to use and modify this datastructure:
$countries = @{            
    "Norway" = "Oslo";            
    "Denmark" = "Copenhagen";            
    "Sweden" = "Stockholm";            
    "Germany" = "Berlin";            
    "Italy" = "Rome";            
    "Burkina Faso" = "Ougadougou";            
};             
            
            
$countries.'Burkina Faso'            
$countries.ContainsKey('Norway')            
$countries.ContainsValue('Ougadougou')             
$countries.ContainsValue('London')            
$countries['Sweden']             
$countries.Add('France', 'Paris')             
$countries.France             
            
$countries.Remove('Burkina Faso')             
            
$countries.ContainsKey('Burkina Faso')
The code above creates a hashtable using the @{ and } literals, where each key and value is defined by key = value followed with a semicolon, note that this is optional and can be omitted. Hashtables are very user-friendly in Powershell. One can address a value in the hashtable by passing in the key in square brackets, like an index. It is also possible to perform manipulation of the hashtable, using Remove and Add. For the Add method, one supplies the key and value pair to add. For the Remove method, one supplies to the key to look for and then remove (this will of course also remove the value of the key-value pair).

It is also possible to query the hashtable using ContainsKey and ContainsValue methods, looking for keys or values. Note also that members of the hash table is available and shown in Intellisense using the Powershell ISE (Integrated Shell Environment). It is possible to say $countries.France, or $countries.'Burkina Faso'. The last hash table key address is encapsulated in quotes, since there is a space in the key. When calling GetType() on the hashtable instance $countries, the name Hashtable is shown.

To list up the keys and the values of a hashtable, use the Keys or Values member of the hashtable. Example:
$countries.Keys            
$countries.Values

Share this article on LinkedIn.

No comments:

Post a Comment