Tome's Land of IT

IT Notes from the Powertoe – Tome Tanasovski

Powershell – Part 4 – Arrays and For Loops

Arrays

For those that have never worked with arrays here’s a great way to understand them:  If a variable is a piece of paper then the stack of papers is an array.  It’s a list of variables or objects, and every programming/scripting language has ways to store these variables or objects linearly so you can access them later via a number of different methods.

So let’s look at how we can create an array of string objects in powershell:

$array = @("test1", "test2", "test3")
$array

You can also add an element to the end of an array:

$array = @("test1", "test2", "test3")
$array += "test4"
$array

You can also add arrays together:

$array = @("test1", "test2", "test3")
$array2 = @("test4", "test5")
$array = $array + $array2
$array

You can access an element of an array if you know the index number of the element you want.  Arrays are indexed by integers starting with 0.  This can be seen with the following code:

$array = @("test1", "test2", "test3")
"First array value: " + $array[0]
"Second array value: " + $array[1]
"Third array value: " + $array[2]

You can use that element as if it’s a regular variable at this point.  Since our array is an array of strings we can use string functions as if this was a regular variable set to that string value when we call the element of this array.  e.g.:

$array = @("test1", "test2", "test3")
$array[1].ToUpper()

For Loops

Arrays can also be accessed linearly through the help of for loops.  A for loop generally has 3 bits of information in their declaration:

  1. Initialization
  2. Condition to continue the loop
  3. A repeating occurrence – This is generally used to bring your loop closer to not meeting the condition for you loop so that the loop will eventually end.

This is best seen by looking at a simple loop.  The following will initialize by setting $i to 1.  It will then test that $i is less than 6 and increase $i by one on each pass of the loop:

for ($i=1;$i -lt 6; $i++) {
	"This is line number " + $i
}

In the above example we use the -lt comparison operator to test that the value of $i is less than 6.  There are many other comparison operators available like -gt (greater than), -le (less than or equal to), -ge (greater than or equal to), -eq (equal), and -ne (not equal).  To learn about the comparison operators available to you can use the following command:

help about_comparison_operators

For Loops with Arrays

It’s easy to see how you can apply a loop to an array to iterate through each element of the array in order if only there was a way to test for how many elements are in the array.  We can do this by using a member of the array object called Length.  The thing to note here is that you want to initialize your index variable with 0 since that is the first element in your array, but you want to test that your index is less than the array length since the last element of the array will be one less than the number of elements in the array.   Here is the process in practice:

$array = @("test1", "test2", "test3")
for ($i=0; $i -lt $array.length; $i++) {
	$array[$i]
}

An even faster way to do a for loop is by using a special foreach loop.  The foreach loop will set a variable to each item in a list with a much simpler construct:

$array = @("test1", "test2", "test3")
foreach ($element in $array) {
	$element
}

The final thing to note with the foreach loop is that it can be accessed via the pipeline.  The foreach that is used in the pipeline is actually an alias to ForEach-Object. Using the pipeline this way is a faster way to write a foreach, but it can incur some overhead when dealing with large data sets. When you use foreach through the pipeline you are given a special variable to represent the element in your code block, $_:

$array = ("test1", "test2", "test3")
$array |foreach {
	$_
}

We have already seen the foreach loop in action in the pipeline during Part 2 of this series when we looked at how to read files.  Here’s a snippit of that code so you can see how a cmdlet can pass a list through a foreach loop:

Get-Content dictionary.txt | foreach {$_.toupper()}

Lists and arrays are very important to programming and scripting.  There is rarely a script that does not use an array or a list in some form or another.  Armed with this knowledge you can start looping away.  We’ll be touching on regular expressions in the next tutorial.  Until next time…

Advertisements

3 responses to “Powershell – Part 4 – Arrays and For Loops

  1. Mr.Anonymoose June 17, 2011 at 9:20 am

    Thank you very very very very very very very much! Your website is a pleasure to look at and one particular piece of code is perfect for looping through arrays. Thanks again!

  2. lygris January 26, 2012 at 2:25 pm

    I just want to give my thanks for the great guide. I’ve been brushing up my Powershell for a job interview tomorrow and your tutorial has been a fantastic help.

  3. Ian November 9, 2015 at 6:27 pm

    I have been learning PowerShell for the last 2 weeks and really like this site, it is full of very good explanations.

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: