12.5 C
New York
Wednesday, November 30, 2022

How to Use a PowerShell Array – Petri.com

New E-Book
Tracking Tasks in Microsoft 365
New E-Book
Microsoft Teams Backup
Latest EBook
Microsoft 365 Backup for Dummies
On-Demand Webinar
Project Management Best Practices Using Microsoft 365
Michael Reinders
Oct 19, 2022
A PowerShell array is a data structure designed to store an item or a collection of items. These item types can be the same or of varying types.
In this article, we’ll explain how PowerShell arrays work, how to use an array of objects, and everything you need to know about PowerShell arrays to become a power user.
Table of Contents
As you may already know, arrays are used by most programming languages. Starting with PowerShell 3.0, a collection of zero or an object has at least some properties of arrays.
A PowerShell array is your answer whenever you need to gather or even manipulate multiple pieces of data, especially when you’re using PowerShell scripting. That’s because when working with an array, you can use a single command to perform the same service on a collection of items or individually manipulate them. It provides a beautiful and adaptable tool in this regard.
There are several different data types you can have in an array including Object and Int32. Each of the items in an array can contain any number of these data types. This is precisely what makes them so versatile.
Each of the data items has an index. Somewhat strangely, the index starts at 0. The first item in an array will be given an index of zero, and the next, 1. And so on…
We’ll learn more about the different types of arrays and their syntax throughout the remainder of this guide.
By illustrating what a PowerShell array is with an example, I’ll be able to show you how this works easily.
First, let’s create an object array with the following command:
We can determine the type of the array with the GetType() command.
Then, let’s try an [int32] or integer array.
From the first example, we see it’s an ‘Object’ array. The second is an ‘integer’ array. 
Alright, let’s create some content, shall we? Again, a PowerShell array can take any type of data. An array type defines the structure of data. We will also pursue creating arrays that can take only specific types of data, per our wishes.
Let’s start with creating an array that will contain any data type. We’ll create an array variable – ‘$ArrayOne’.
Per our previous example:
Because we didn’t specify a data type, the array can take any. However, I’ll now show you how to create an array while specifying a specific data type. We will prepend the variable name with the data type. Watch this:
I’ll sneak another topic here – the strongly typed array. We can set an array to ONLY contain a specific data type. As an example, this command will force the array to only allow integers:
Next, I’ll describe how we can add, remove, and append data on an existing array. Actually, up to this point, we’ve created arrays adding data right from the start. The default size of arrays, incidentally, is defined by the initial creation of the array.
Let’s first create an empty array:
I know, not much there. So, before we add an entry to this array, we need to convert it into a list so it can accept additional indexed entries of data. We accomplish this with the [System.Collections.ArrayList] command:
We’ve created a new ‘list’ array – FileNamesList – based on our existing and empty ‘$FileNames’ array. Then, we added the first indexed entry (at 0) – ‘Patterns’ – Not too bad, huh? I’ll add a few more items to our array, then show you how to remove an item or two.
And, by the way, you can get easy access to your array elements by typing the variable name by itself – ‘$FileNamesList’ above.
Let’s remove the last data piece – ‘Complete’. We use the corresponding Remove command.
Piece of cake.
It’s pretty easy to make a change to an item in your array. As long as you know the index record of the data point you wish to change, you can make the change right away.
First, let’s list the contents of our ‘$FileNamesList’ array:
Here, I would like to update the 2nd entry (Index ‘1’) from ‘Embroidery’ to ‘Secondhand’. Here’s how to do it:
I do like how simple the manipulations of arrays can be, don’t you?
One of the most powerful aspects of PowerShell is being able to perform repetitive actions or tasks on many objects at once. In a similar fashion, we can add a description to the beginning of our data points by using the ForEach-Object command.
Let’s try adding ‘Preferred’ at the beginning of our data points:
Very cool.
Pretty much all of the operators that we use for single data items in PowerShell also work with arrays. However, there are some differences. Let’s take a look at the most common operators and how you can use them in your arrays.
The join operator is arguably the most often used command in PowerShell, and it’s extremely useful when working with arrays. You can use it iteratively (efficient!) on the items in an array to join items together for the output purpose.
Let me show you how it works. First, we’ll create an array:
Then, we’ll use the ‘-join’ command to add a ‘-‘ in between each item when showing the output.
Very nice. It’s relatively easy to discover how these operators could make it simple to manipulate on-screen data and even logged output!
We can use the contains operator to find out if an array has an existing data point or not. The Boolean True or False terms signify to us the answer.
My goodness, even a Ferengi could figure THIS out…
Lastly, I’ll explain a subtle difference in how to use the equals and not equals comparison operators. These are the same as -eq and -ne.
When you use the -eq switch, PowerShell will output the value if it is True, not False. The –ne switch (not equal) will output every value in your array that does NOT match your request. Yes, it’s a little different.
Let me show you how it works with an example:
On the first line, it simply outputs the entry matching the request, ‘200’. On the second line, it listed all the array members that were not equal to ‘100’. Using the correct format (syntax) of these commands is crucial!
You can also create a multi-dimensional array by altering the syntax of the array. This allows you to easily create a multi-data type array from the start.
Let me show you an example:
The second command requests the output of the data entry at the row and column of [1,1]. Think about this as an Excel table where we’re looking at the cell in the second column over and the second row down.
You’ve seen an example or two sprinkled into my post thus far on how to retrieve the information in an array. Let me show you the basic syntax on how to do this for your arrays.
If we look at our $List array, we see 5 indexed entries. If we want to retrieve the third entry, we use the index of ‘2’.
There are two fundamental examples of using ForEach with PowerShell arrays – the method and the loop. We use this to process every item in an array to gather the information we’re looking for, or to manipulate all the entries in our array at once. 
To use the ForEach Method to loop through an arrayhere’s how we will proceed:
Let me show you an example. We can get the 10 newest entries from the Event Viewer from each of the 3 ‘core’ log types – System, Application, and Security. We just separate each entry with a comma.
We first store the 3 types of logs in our variable. Then, we use the ForEach method to grab the 10 newest log entries from each type and output them. Very powerful, and very efficient.
Now let’s use a similar loop structure (script block) to perform the same request. The main difference here is instead of using ‘$_’ as a temporal variable, we store each run-through in a temporary variable (LogNames).
Let me show you how it works with an example:
Voila. And, let me point out a massive performance boost in using PowerShell vs. the GUI. Running this command, which outputs the 10 most recent log entries from the System log, the Application log, and the Security log takes a blink of an eye. Opening the Event Viewer MMC tool, navigating to each of these logs, and saving the most recent 10 entries takes a minute even on a fast computer. What amazing time savings!
So far, we’ve shown you how to create an array with basic data. Most notably a string or an integer. However, arrays can also contain objects. Many of the most common uses of PowerShell, especially when working in Office 365 dictate that you use objects instead.
We can use similar functions to create an array of objects. It’s all about the syntax. We’ll create a (very) basic directory of users. Let’s use this example.
We’ve entered the two names into the array and shown the output. Nice and easy. We can also access the individual properties of each object by specifying them as we’ve done already.
As this is index #1, we know this is the second entry. So, we should get back ‘Michael’. Let’s see.
Yes, that worked as expected!
Using similar syntax, we can iterate through our entries and make a change. Let’s say Billy got married and is taking his spouse’s last name (Jones). We can update our array with one step!
You have to hand it to Microsoft, they really built a nice scripting language.
I’d like to show a more pointed example of going through our entire array for a purpose. We can access the same property of all of our objects and get that output using the ForEach-Object cmdlet.
Lastly, I’ll show you some more advanced array functions in your arsenal that can definitively boost your efficiency when scripting with arrays.
Taking a step back briefly, creating an array up to this point we’ve determined the size of the array by the number of items in it. However, we can create a pre-sized-array, which is an array with a specified size.
To create a pre-sized array, we’ll use the new($size) constructor. Here’s an example.
Even though there are no entries yet in our new array, the ‘Count’ does list 8 (empty) entries.
Multiplying arrays can be rather confusing for some users, but it really comes down to repeating values the specified number of times. Let me show you.
Here, we simply took the original 3 entries and multiplied them 3 times. Now we have 3 *3 = 9 entries.
Similar to other programming languages, we can use nested arrays to create a classic matrix, so to speak. Let me demonstrate with a two-dimensional array.
So, first, we add the 9 entries to the array, 100 – 900. Then, when we specify the second command, we are asking for the entries in the first row and the third row. And, with the last command, we are asking for the single entry at row 0, column 2 – ‘300’. Piece of cake!
Well, I hope you learned as much as I did! Yes, seriously, I am on a learning module of sorts with PowerShell as I go through this series of posts. Catching up on some of the ‘basics’ of PowerShell is ALWAYS fruitful for me. I often times use something I learned or re-learned just days before in my professional IT life.
If you have any questions or comments, please feel free to leave a comment below. Thank you for reading!
More from Michael Reinders
How to Use a PowerShell Array
Filtering with PowerShell Where-Object: Easy Examples
How to Run Commands and Programs Remotely Using PsExec
Petri Newsletters
Whether it’s Security or Cloud Computing, we have the know-how for you. Sign up for our newsletters here.
More in PowerShell
How to Use a PowerShell Array
Oct 19, 2022 | Michael Reinders
Filtering with PowerShell Where-Object: Easy Examples
Oct 10, 2022 | Michael Reinders
What is PowerShell and How to Get Started With It?
Sep 7, 2022 | Mike Kanakos
Use a PowerShell Substring to Search Inside a String
Aug 11, 2022 | Jeff Hicks
Test Network Connectivity with PowerShell Test-Connection
Aug 9, 2022 | Jeff Hicks
How to Use the PowerShell Exit Keyword to Terminate Scripts
Aug 8, 2022 | Ivan Mirchev
Most popular on petri
Article saved!
Access saved content from your profile page. View Saved
Reach out
Learn More
Join The Conversation
Create a free account today to participate in forum conversations, comment on posts and more.
Copyright ©2019 BWW Media Group
Terms and Conditions of Use


Related Articles


Please enter your comment!
Please enter your name here

Latest Articles