...

Programming languages - Powershell

Back to Course

Lesson Description


Lession - #115 PowerShell-Hashtables


Hash Tables (otherwise called Associative arrays or Dictionaries>
are a sort of exhibit that permits the capacity of paired Keys and Values, rather like a basic database table.

Not at all like typical arrays where you allude to every component through a numeric index, the keys of a hash table can be strings. The Key qualities in all actuality do in any case should be special, assuming you attempt to add a similar key two times PowerShell will return a error ("thing has proactively been added">
.

The implicit properties of a powershell hashtable incorporate .Keys .Values and .Count

Pronouncing hashtable Variables
To utilize a hashtable in a program, you should pronounce a variable to reference the hashtable. Here is the language syntax for announcing a hashtable variable −

Syntax

$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
or
$hash = @{}

Example
The following code snippets are examples of this syntax −
$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"}

Print the hashtable.
$hash

Output

Name                           Value    
----                           -----                                                    
ID                             1                                                        
Color                          Blue                                                     
Shape                          Square 
Processing Hashtable
Dot notation can be used to access hashtables keys or values.
$hash.keys
ID
Color
Shape

> $hash.values
1
Blue
Square


Example:
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}

write-host("Print all hashtable keys">
$hash.keys write-host("Print all hashtable values">
$hash.values write-host("Get ID">
$hash["ID"] write-host("Get Shape">
$hash.Number write-host("print Size">
$hash.Count write-host("Add key-value">
$hash["Updated"] = "Now" write-host("Add key-value">
$hash.Add("Created","Now">
write-host("print Size">
$hash.Count write-host("Remove key-value">
$hash.Remove("Updated">
write-host("print Size">
$hash.Count write-host("sort by key">
$hash.GetEnumerator(>
| Sort-Object -Property key