Powershell Simplified Part 2: Arrays and Hashtables

Today we’ll do some Powershell programming using some basic constructs. First let’s take a look at arrays in Powershell, turns out they are not much different from arrays in C#.

Try out these in a PS1 file (to run the ps1 file see the instructions in Part 1 of this series),

$array = @(1, "Hello", 3.14)                     # create a mixed Powershell array 
write-host “array length is” $array.length       # output the length of the array 
$array += "World"                                # append to the array  
write-host “third element is” $array[2]          # get the 3rd element in the array $array[3] = "Powershell"                         # update an element in the array $array = $array | Sort-Object                    # sort the array write-host “sorted array:” $array           # sorted array: 1 3.14 Hello Powershell $array = $array[0..1] + $array[3]           # remove the 3rd element from the array write-host $array $array = @()                                     # clears the array

Use foreach to loop through the array: foreach ($element in $array) { write-host $element }
Search the array for an item: $array –contains “2.18” (this evaluates to false in our case)
We can also wildcard search for an item: $array –like “He” (this evaluates to true in our case)

A hashtable also works as you would expect in Powershell,

$htable = @{UK = "London"; Austria = "Vienna"; France = "Paris"} # create a hashtable 
write-host $htable["UK"]                       # get the value of a key 
write-host $htable.France                      # another way to get a value 
write-host $htable.keys                        # get all the keys 
$htable["US"] = "Washington D.C."              # insert or update a key 
$htable.add("India", "New Delhi")              # another way to insert 
$htable.remove("UK")                           # remove a key 
foreach ($key in $htable.keys) { write-host $key ":" $htable[$key] }   # enumerate

Use ContainsKey or ContainsValue to search inside the hashtable: $hashtable.ContainsKey("India")

Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

One Response to Powershell Simplified Part 2: Arrays and Hashtables

  1. Pingback: Powershell Simplified Series « I.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: