PowerShell How-To

Managing Arrays in PowerShell

How to read, add and modify array elements -- with a few curve balls along the way.

In PowerShell and many languages, an array is a set of items all represented by a single variable. To explain arrays and how to manage them in PowerShell, let's start with the example of a set of colors. If a group of items is related to one another, it's always a good idea to keep them as a "set" by putting them all into an array.

Maybe I'm creating a color picker in a bigger script and I'd like to reference each color in a single variable. I could create an array called $colorPicker to do this. I'll tell PowerShell that I intend this to be an array and will insert each color as an item inside by using the "at" sign and opening and closing parentheses.

PS C:\> $colorPicker = @('blue','white','yellow','black')
PS C:\> $colorPicker
blue
white
yellow
black

Reading Array Elements
I now have a list of all colors in one variable. I can now reference each of these colors by index number starting with zero. Just don't try to specify an index number that's higher than what's actually in the array.

PS C:\> $colorPicker[0]
blue
PS C:\> $colorPicker[2]
yellow
PS C:\> $colorPicker[3]
black
PS C:\> $colorPicker[4]
Index was outside the bounds of the array.
At line:1 char:1
+ $colorPicker[4]
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], IndexOutOfRangeException
    + FullyQualifiedErrorId : System.IndexOutOfRangeException

We can also change arrays on the fly by assigning new values to the index numbers.

PS C:\> $colorPicker[3]
black
PS C:\> $colorPicker[3] = 'white'
PS C:\> $colorPicker[3]
white

Adding Array Elements
Perhaps you've created an array like our $colorPicker example and need to add some additional colors to it. Instead of completely removing the existing array and creating a new one, we can add items to one using the + operator. The + operator in PowerShell is used to add items to various lists or to concatenate strings together.

To add an item to an array, we can have PowerShell list all items in the array by just typing out its variable, then including + <AnotherItemName> behind it.

PS C:\> $colorPicker = $colorPicker + 'orange'
PS C:\> $colorPicker
blue
white
yellow
black
orange

The + method works, but we have a shorter, more common way to accomplish the same thing. Instead of just using the + operator, we can use the plus and equals signs together to form +=.

PS C:\> $colorPicker += 'brown'
PS C:\> $colorPicker
blue
white
yellow
black
orange
brown

The += operator is a shortcut that tells PowerShell to add this item to the existing array. This shortcut prevents you from having to type out the array name twice and is much more common than using the full syntax.

Modifying Array Elements
Modifying array elements is easy. We merely need to find the item we'd like to change using the index number and assign a new value to it.

In our color picker example, perhaps I want to change the white element to the color pink. I'd first need to figure out which index the white element is defined under. Since we have a small array and I know the index number of white is 1, I can simply set another value just like I'm setting a value on a simple string variable.

$colorPicker[1] = 'pink'

That's it! Modifying array elements is a piece of cake.

Not All Arrays Are Alike
Recall earlier that I told you that you could add elements to an array and that it looks like I did using the += operator? Well, I lied. PowerShell makes you think you're adding elements to an existing array, but you're technically creating a new one anyway; it just doesn't look like it.

Why bring this up now? The reason is that I've just walked you through reading, adding and modifying array elements. It would only be prudent of me to show you how to remove them, as well. But when I did that, you'd see that the method to remove an element from a typical array in PowerShell isn't possible. PowerShell arrays are of a fixed size. Here's the proof:

PS C:\> $colorPicker.Remove('brown')
Exception calling "Remove" with "1" argument(s): "Collection was of a fixed size."
At line:1 char:1
+ $colorPicker.Remove('brown')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NotSupportedException

When you need to remove elements from an array, PowerShell destroys the old one and creates a new one. You'll typically not notice this, but when you begin to work with huge arrays with tens or hundreds of thousands of elements, you'll see a significant performance hit. Instead, we can use a similar type of array known as an ArrayList. An ArrayList behaves nearly identical to the typical PowerShell array but is not a fixed size.

For example, to create our color picker array as an ArrayList, we just need to cast the array to a System.Collections.ArrayList type. We'll learn a lot more about casting and object types in a little bit.

PS C:\> $colorPicker = [System.Collections.ArrayList]@('blue','white','yellow','black')

We now can use methods on this object to add and remove elements from the array without recreating it. Once we have an ArrayList, we can use the Add() and Remove() methods to add or remove items from the array. I'm using the term "array" loosely here. From now on, a PowerShell array and an object of type System.Collections.ArrayList is one and the same for us.

To add elements to an array now, we can use the Add() method and pass the element in as the method's argument.

PS C:\> $colorPicker.Add('gray')
4

Notice, though, that it returned something: the number 4. Where did that come from? The Add() method in an ArrayList will always return the index number of the element that was just added. Typically, we don't care about this number so you'll usually see the Add() method sent to $null to not return anything.

PS C:\> $null = $colorPicker.Add('gray')

Since we've got a "fancier" array to work with now, we can use the Remove() method to remove whatever elements we need to. In the previous example, we added an element with the value of gray, and from the number 4 that was returned, we know that index is 4. Let's remove it.

PS C:\> $colorPicker.Remove('gray')

Notice this time that we don't have to know the index number at all. We can reference the element by its actual value. This "more advanced" array does have a few advantages over the typical PowerShell array such as increased performance when adding items, the ability to remove elements from an array and a few other things. If you're interested in digging deeper into array lists, check out all of its properties and methods with Get-Member.

PS C:\> ,$colorPicker | Get-Member

Working with arrays in PowerShell is a fairly straightforward process once you get the hang of it. The biggest challenge for most beginners is figuring out when to use an array. As a rule of thumb, if you find yourself needing to perform an action of any kind on one or more items, chances are that your best bet is to use an array.

About the Author

Adam Bertram is a 20-year veteran of IT. He's an automation engineer, blogger, consultant, freelance writer, Pluralsight course author and content marketing advisor to multiple technology companies. Adam also founded the popular TechSnips e-learning platform. He mainly focuses on DevOps, system management and automation technologies, as well as various cloud platforms mostly in the Microsoft space. He is a Microsoft Cloud and Datacenter Management MVP who absorbs knowledge from the IT field and explains it in an easy-to-understand fashion. Catch up on Adam's articles at adamtheautomator.com, connect on LinkedIn or follow him on Twitter at @adbertram or the TechSnips Twitter account @techsnips_io.


comments powered by Disqus

SharePoint Watch

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.