Powershell to the people
Arrays and filters— Part 3
Please share this tutorial, that inspires me to continue doing this tutorial series.
Previous parts
Arrays
Before we can continue with the filtering we need to understand what arrays are in Powershell. Arrays are a collection of objects that you can iterate through to find something or organise a data structure. You can think of array like a basket of fruit and you can have multiple baskets, one for vegatables and one for fruits. If we take a look at how the structure of array is then you can see it is very simple
$basket = “apple”,”orange”,”banana”,”kiwi”
You can print out how many objects are in this example by using the count method which is available in all objects or you can also write out the specified object in specific index of the basket, as seen in the image below.
As you can see in the image above that we can count how many objects are in the array and also what index of apple is. Now arrays always start from 0 until the last object. You can iterate through the array by using foreach as seen in the example below.
#iterate through the listforeach($fruit in $basket){ write-host "We have $fruit in the basket"}
This is just a simple example on how we implement an array, when we start to utilize Powershell much more then we can see how arrays are powerfull and how we can use them to help us find data using filters.
Filters
When you are developing in Powershell you must know how to filter. Filtering is one of the most power-full feature in Powershell because you can manipulate the data based on your needs and it is really simple to use. To understand filtering we can use arrays to find data. Lets say that we have a basket of fruits and we want to find every fruit that has the letter “a” in it. So we do the following command
$basket | where { $_ -like "*a*" }
As you can see in the screenshot above it does not show “orange” or “kiwi” but only the words that contain the letter “a”. Now there are more operators that you can use and the operator in the screenshot above is “-like”. Here are list of common operators that I use regularly
# finds something that is like something
-like# finds something that is not like something
-notlike# find something that is exactly this, same as equal
-eq# find something that is not exactly like this, is not equal.
-ne
There are more operators but I will not get into that now.
Continue with the next part of this series
Part 4