Tag Archives: Array

Fun With PowerShell Arrays

Introduction

In this article, we’ll look at the different ways to use Arrays in PowerShell. We’ll cover the basics, then move onto more advanced topics.

For all of the examples, we’ll display the code, then under it the result of our code. In this article I’ll be using PowerShell Core, 7.1.3, and VSCode. The examples should work in PowerShell 5.1 in the PowerShell IDE, although they’ve not been tested there.

To run a snippet of code highlight the lines you want to execute, then in VSCode press F8 or in the IDE F5. You can display the contents of an array variable (or any variable) by highlighting it and using F8/F5.

A quick note for my non-native English speaking friends, I use the term aka a few times. AKA is shortcut for “also known as“, it’s just a quick way to say “a is another word for b”.

Array Basics

The formal array to declare an array is to use @() around the contents, assigning it to a variable.

$array = @('Robert', 'Cain')
$array

Result:
Robert
Cain

Note that in the output, each item (aka element) in the array is displayed on a single line.

There is a little easier way to create an array, you can omit the @() . If you are passing in more than one item, separated by a comma, PowerShell converts it to an array.

$array = 'Robert', 'Cain'

If you have a long list of items, you can break the list over multiple lines. As long as a comma is the last thing on the line PowerShell will assume the rest of the array contents continue on the next line.

$array = 'Robert',
         'Cain'

You can access individual items in the array by using what is called positional notation. After the name of the array, use square brackets [] and inside put a number that indicates the position in the array.

Numbering begins at zero and goes to the maximum number of elements. (Well, technically the max number of elements minus one, but more on that in a moment.) If you try to use a number greater than the maximum number of elements, you will get an error.

$array = 'Robert', 'Cain'
$array[0]

Result:
Robert

$array[1]

Result:
Cain

Of course you can use variables in place of the numeric values for positional notation.

$x = 1
$array[$x]

Result:
Cain

So how do you know how many items are in an array? The array variable type has a Count property that can tell you that.

$array.Count

Result:
2

There is also a property called Length, which returns the same thing. They can be used interchangeably, most people however use the Count property.

One thing to be careful of with Count, is that it returns the number of items in the array. But arrays start with position 0 (zero), so the last item in an array will be Count - 1, not Count.

$array[$array.Count - 1]

Result:
Cain

PowerShell does provide a shortcut to get the last element. You can pass in a -1 (negative one) into the position, and it will get the last item.

$array[ -1 ]

Result:
Cain

Fun Tricks with Positional Notation

There are a few fun tricks you can do with positional notation. So far, we’ve only used a single value in the square brackets to get a single value from the array.

Did you know you can pass in multiple numbers and get back multiple elements from the array in one command?

$array = 'Zero', 'One', 'Two', 'Three',
         'Four', 'Five', 'Six', 'Seven'
$array[2, 4, 6]

Result:
Two
Four
Six

If you pass in the same number twice, you’ll get that array item back twice in the results.



$array = 'Zero', 'One', 'Two', 'Three',
         'Four', 'Five', 'Six', 'Seven'
$array[2, 4, 2]

Result:
Two
Four
Two

Finally, you can use PowerShell’s range operator to return a series of values.



$array = 'Zero', 'One', 'Two', 'Three',
         'Four', 'Five', 'Six', 'Seven'
$array[1..4]

Result:
'One'
'Two'
'Three'
'Four'

Adding Items to an Array

Adding items is pretty easy, you can use the += (plus equal) to add a new item into the array. In this example, we’ll add two new items, then display the new array, and finally the count of items.

$array = 'Robert', 'Cain'

$array += 'Arcane'
$array += 'Code'
$array

$array.Count

Result:
Robert
Cain
Arcane
Code
4

Here you can see are my original two items, followed by the new ones we just added. Finally the count, 4, is displayed.

Updating an Array Element

What if we want to update a value in the array? Turns out that is as easy as adding a new one. Simply address the item to replace with positional notation, then assign a new value.

$array[0] = 'Mr.'
$array

Result:
Mr.
Cain
Arcane
Code

Empty Arrays

When you need to create an empty array, you use the formal array declaration syntax we saw in the first example, only you put nothing in it.

$empty = @()
$empty

Result:
(Nothing is displayed because the array is empty)

So why would you need an empty array?

Let’s say you were looping over a collection of some type, and were building a new array to output. It might be a collection (aka array) of files, or records return from a SQL Server query.

You would create the empty array, enter the loop, extract and format the information you want then add it to the empty array using the += syntax.

Iterating Over Arrays

There are a few methods we can use to iterate, or loop over the contents of our arrays. The most common, and one I use the most, is a foreach loop.

foreach($item in $array)
{
  "The current item is $item"
}

Result:
The current item is Mr.
The current item is Cain
The current item is Arcane
The current item is Code

The next option is to pipe our array into the ForEach-Object cmdlet, passing a script block to the cmdlet with our instructions.

$array | ForEach-Object { "Current Value: $PSItem"}

Result:
Current Value: Mr.
Current Value: Cain
Current Value: Arcane
Current Value: Code

The variable $PSItem is a built in PowerShell variable, meant to represent the current item in a loop.

Finally, an Array datatype has a ForEach method built right in. You call the method, then as you did with the ForEach-Object cmdlet pass in a script block with the instructions.

$array.ForEach({ "Current Value: $_"})

Result:
Current Value: Mr.
Current Value: Cain
Current Value: Arcane
Current Value: Code

In this example we used the variable $_ to represent the current item. The $_ was the original way to create a placeholder, later PowerShell added the $PSItem variable. $PSItem was introduced way back in version 3, so unless you are on a really really REALLY old version of PowerShell, you can use $_ and $PSItem interchangeably.

Erasing the Contents of an Array

Clearing out the contents of an array is easy, just call the array’s Clear method.

$array.Clear()
$array

Result:
(Nothing is displayed because the array is empty)

Mixed Data Types

Unlike a lot of other languages, the values going into an array can be a mix of data types. In the example below I’m going to load an array with some strings, integers, and a floating point type.

$array = 'Arcane', 'Code', 33, 42,
         'Alabama', 3.14, 'In the Morning'
$array

Result:
Arcane
Code
33
42
Alabama
3.14
In the Morning

Removing Items From Arrays

We now move to a topic that doesn’t have a happy answer. You cannot remove an item from an array. That said, you could create a brand new array, filtering out the unwanted elements.

In this example, we pipe our array into the Where-Object cmdlet. We pass in a script block, in which we say only pass out items where the value of the current item is not equal ( -ne ) to the state of Alabama. After that we display the results.

Note too we are using another built in line continuation feature of PowerShell. If the pipe symbol, a | , is the last thing on the line PowerShell assumes what is on the next line is a continuation of the line above. (I like to indent the second line to the right of my equal sign, but it’s not required.)



$array = 'Arcane', 'Code', 33, 42,
         'Alabama', 3.14, 'In the Morning'
$newArray = $array |
            Where-Object { $PSItem -ne 'Alabama' }
$newArray

Result:
Arcane
Code
33
42
3.14
In the Morning

As you can see, the state of Alabama is no longer in our list.

Fun Operators – In and Compare

There are other operators in PowerShell that can let us do fun things with arrays.

First, what if we need to know if an item is already in the array? There’s actually two methods to handle that. In the first, we’ll see if the item is in the array.

$array = 'Arcane', 'Code', 33, 42,
         'Alabama', 3.14, 'In the Morning'
'Arcane' -in $array

Result:
True

In the second method we’ll use the contains operator.

$array -contains 'Code'

Result:
True

More Fun Operators – Join

What if you wanted to convert all of the elements in the array into a single string? To handle that we have the join operator.

After the join, you pass in a character to use to separate each element. You also have the option to pass in an empty string if you don’t want anything separating your results.

In the last example, you’ll see that you can pass in more than one character to separate the results.

$array = 1, 3, 5, 7, 9
$result = $array -join ' '
$result

Result: 1 3 5 7 9

$array = 1, 3, 5, 7, 9
$result = $array -join '-'
$result

Result: 1-3-5-7-9

$array = 1, 3, 5, 7, 9
$result = $array -join ','
$result

Result: 1,3,5,7,9

$array = 1, 3, 5, 7, 9
$result = $array -join ''
$result

Result: 13579

$result = $array -join ', '
$result

Result: 1, 3, 5, 7, 9

Even More Fun Operators – Replace, Match, Split

There are three more operators we’ll cover here. The first is Replace, which will search through the array and replace one string with another.

$servers = 'HOLD-001', 'HOLD-002', 'SQL-001', 'SQL-002'
$newServers = $servers -replace 'HOLD', 'TEST'
$newServers

Result:
TEST-001
TEST-002
SQL-001
SQL-002

You might use this to develop a script to run against your servers. When designing the script you might use a string like HOLD-001, HOLD-002, etc where HOLD is just a place holder.

At runtime you pass a parameter into your script such as DVLP (development), TEST, or PROD (production) so you can use the same script in multiple environments.

The next operator we’ll look at is match. Match can be used as a filter. Let’s take a look at this example:

$servers = 'SRV-001', 'SRV-002', 'SQL-001', 'SQL-002'
$newServers = $servers -match 'SQL'
$newServers

Result:
SQL-001
SQL-002

As you can see, only servers with SQL in the name were returned. This might be useful if you had a full list of all servers you wanted to iterate over, but in certain sections of your script you only wanted to do things to your SQL Servers.

The final operator to look at is split. You can use split to further divide the elements in your array into smaller parts.

In this example we’ll reuse our list of servers, but split the items based on a dash (or hyphen).

$servers = 'SRV-001', 'SRV-002', 'SQL-001', 'SQL-002'
$newServers = $servers -split '-'
$newServers

Result:
SRV
001
SRV
002
SQL
001
SQL
002

Here you can see each server name was split into two parts, each part becoming a new element in our output array. Also note that the character we split on, the dash, is discarded from the result set.

Iterating Over an Array of Objects

Just like arrays of simple items like strings and integers, you can also loop over an array of objects.

Here, we’ll get a list of files in my temp directory using the Get-ChildItem cmdlet. We’ll also use the empty array technique you saw earlier. A foreach loop will be used to go over each file object in the array and format a string with some of its properties, then add that string to our empty $newFiles array.

Set-Location "C:\Temp"
$files = Get-ChildItem
$newFiles = @()
foreach($file in $files)
{
  $newFiles += "$($file.Name) is $($file.Length) in size"
}
$newFiles

Result:
2019-ARRL-FieldDay-Rules-RevA.pdf is 111434 in size
ARRL-FIELD-DAY.adi is 76110 in size
azuredatastudio-windows-user-setup-1.13.1.exe is 91789368 in size
curl-7.74.0.zip is 6068670 in size
standard-notes-3.6.14-win.exe is 105761936 in size
SysinternalsSuite.zip is 41889407 in size

Within my loop $file represents the current item in my $files array. Inside I access the properties of my file object. I could, for example, have used if ($file.Length -gt 1) and done something useful.

In this case I’m using string interpolation to display the value of a property. Note that because I want it to access the property, within the string I have to wrap it in $(), such as $($file.Name).

This forces PowerShell to first evaluate what is inside the $(), then return that into the string.

Conclusion

This post turned out longer than I’d intended, but there are so many fun things you can do with a PowerShell Array it was hard to stop at just a few.

With luck you’ll have found some new techniques you can employ with arrays in your own PowerShell scripts.

The demos in this course came from my Pluralsight course PowerShell 7 Quick Start for Developers on Linux, macOS and Windows, one of many PowerShell courses I have on Pluralsight. All of my courses are linked on my About Me page.

If you don’t have a Pluralsight subscription, just go to my list of courses on Pluralsight. At the top is a Try For Free button you can use to get a free 10 day subscription to Pluralsight, with which you can watch my courses, or any other course on the site.