PowerShell Hash Table


Hash table is a dictionary which also data structure that store key/value pairs. Example a hash table taht contain a series of users data or ip addresses and the computer names. The syntax to define hash table.

@{ <key> = <value>; [<key> = <value>] ...} 

$users = @{
    'name1' = 'Sam';
    'name2' = 'Dani';
    'name3' = 'Jane'
}

$comp_addresses = @{
    'comp1' = '192.168.1.2';
    'comp2' = '192.168.1.3';
    'comp3' = '192.168.1.4';
}

Remember the key in hash table can't be duplicated. To access the value of hash table you simply type hash_variable.key and you can use the key as the index.

$users.name1 # sam
$users.name2 # Dani
$users['name1'] # sam
$users['name3'] # Jane
$comp_addresses['comp3'] # 192.168.1.4

To add a new element in hashes you can use method Add(<key>, <value>).

$comp_addresses.add('comp4', '192.168.1.5')
$comp_addresses.add('comp5', '192.168.1.6')
$comp_addresses.add('comp6', '192.168.1.7')
# you can do this too
$comp_addresses['comp7'] = '192.168.1.8'
# this too
$comp_addresses += @{'comp8'='192.168.1.9'}

To delete the element of hash table, you can use Remove(<key>) method.

$comp_addresses.Remove('comp8')
$comp_addresses.Remove('comp7')
$comp_addresses.Remove('comp6')

You can also use make the hash table to be ordered, you simply just cast the hash table with [ordered]. The hash table will be ordered base on the key.

$comp_addresses = [ordered]@{ # correct way
    'comp1' = '192.168.1.2';
    'comp2' = '192.168.1.3';
    'comp3' = '192.168.1.4';
}

$[ordered]$hash = @{} # this will generate error

Another things you can do in hash table.

$comp_addresses.Keys # print the all key
$comp_addresses.Values # print the all value

$get_proc = @{"PowerShell" = (get-process PowerShell);
"Notepad" = (get-process notepad)}

$get_proc += @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}

$get_proc.keys | foreach {$p.$_.handles}

$get_proc += @{"Hash2"= @{a=1; b=2; c=3}}
$get_proc # display $get_proc
$get_proc.Hash2 # display hash2

Subscribe to receive free email updates:

0 Response to "PowerShell Hash Table"

Post a Comment