PowerShell Arrays: How To Build, Manipulate, and Manage ThemPowerShell Arrays: How To Build, Manipulate, and Manage Them

PowerShell arrays support dynamic operations like adding, modifying, or removing elements, and can also be filtered and manipulated using advanced techniques like slicing, joining, and looping through array items.

Brien Posey

January 17, 2025

12 Min Read
an illustrated laptop with powershell code on screen surrounded by 3d shapes and coding icons like the @ symbol, square brackets, and a filter

Arrays are a fundamental element of nearly all modern programming languages, providing a way to store a sequence of items in a single variable. In PowerShell, arrays can hold various values, such as numbers, strings, or even a mix of different data types.

Zero-Based Indexing in PowerShell Arrays

Arrays in PowerShell are indexed, meaning each item in an array has a positional indicator. These positional indicators allow you to reference individual values within an array. 

For example, to create an array called $Array that holds the numbers 1 through 5, you can use this command: 

 $Array=@(1,2,3,4,5)

The @ symbol tells PowerShell to treat the variable as an array. 

PowerShell arrays use zero-based indexing. The first value (1) is stored at position 0. To retrieve a value, reference its index like this:

  • $Array[0] PowerShell returns 1 (the first value). 

  • $Array[4] returns 5 (the fourth value).

The indexing system makes it easy to access specific elements in your array.

Importance of Mastering PowerShell Array Operations

PowerShell scripts and everyday tasks frequently use arrays. For example, many scripts downloaded from GitHub rely heavily on arrays, and without a solid grasp of how they work, it would be difficult to follow or modify the script’s logic

Additionally, arrays simplify tasks that involve managing multiple items, making them invaluable for handling data, automating processes, and solving complex problems.

Related:Advanced String Manipulation Techniques in PowerShell

Methods for Array Creation and Initialization

PowerShell provides an easy way to create arrays. In the earlier example, the array was populated with data at the time of creation. However, you can also create an empty array and add data to it later. 

Creating an empty array in PowerShell works just like creating a populated array, but without supplying any initial data. The following command creates an empty array that you can populate afterward:

$Array = @()

If you need an empty array with a specific number of indexed positions, you can use a For loop to fill the array with $Null values. For example, to create an array with five positions: 

$Array=@()
For ($I = 0; $I -LE 5; $I++
{
$Array += $Null
}

This approach initializes the array with five $Null entries, which you can later replace with meaningful values. 

Tips for Working with Strongly Typed Arrays

A strongly typed array ensures that all elements conform to a specific data type. For instance, you can create an array that only accepts integers. While PowerShell arrays are typically flexible with data types, using a strongly typed array is helpful when your script requires strict type enforcement. 

You can create a strongly typed array by specifying the desired data type in square brackets ([ ]) as a part of the array definition. Any attempt to assign a value of a different data type to the array will trigger a PowerShell error

Related:How To Convert PowerShell String Data to Integers

For example, to create an integer-only array: 

[int[]]$Array = @(1,2,3,4,5)

This approach will ensure that only integers can be stored in $Array.

Manipulating Array Elements

PowerShell arrays are dynamic, meaning you can add, modify, or even remove items. To manipulate a specific array element, you need to know its position (index) within the array.

For example, if you have an array containing the numbers 1 through 5 and want to change the number 3 to 6, you can find the index of 3 and update that position directly. Alternatively, you could use the Where-Object command, which is often simpler for more complex conditions (we will cover that later). 

 Here is an example of finding the position of 3 within an array and replacing it with 6:

$Array=@(1,2,3,4,5)
$Position = [Array]::IndexOf($Array,3)		# Find the index of the number 3 
$Position					# Display the position (index)
$Array[$Position]=6				# Replace the value at the found index with 6
$Array						# Output the updated array    

 This script updates the array from (1, 2, 3, 4, 5) to (1, 2, 6, 4, 5). 

Accessing and Modifying Array Items

You can access any item within an array by referencing its position in brackets. For instance, to view the value stored at position 2 in an array: 

$Array[2]

Modifying a value in an array is just as simple. You specify the array position and assign a new value, just like you would for any other variable. To replace the value position 2 with 6, you could use this command:

Related:How To Use Dynamic Parameters in PowerShell Functions

$Array[2]=6

Adding and Removing Elements from Arrays 

Adding elements

You can add a value to an array without replacing an existing element. When you add a value, it gets appended to the end of the array, and a new position is created automatically. 

To add a value, use the += operator followed by the value you want to append. For example, to add 6 to the end of an array, use this command:

$Array += 6

Removing elements

Unlike adding elements, PowerShell does not have a direct command for removing an element from an array. To remove an item, you typically need to rebuild the array by filtering out the unwanted value or creating a new array with the desired contents. 

You can read an article on the subject here.

You can also find an example of this process in the FAQ section at the end of this article.

Advanced Array Manipulations

While most PowerShell scripts focus on basic array operations, PowerShell also provides many advanced techniques for working with arrays, such as slicing, joining, and splitting arrays.

Slicing arrays 

Slicing an array refers to extracting a subset of the array’s contents. For instance, if you have an array with six elements and want to slice it in half, you can create two new arrays, each containing three elements. 

Here is what the operation would look like: 

$Array=@(1,2,3,4,5,6)
$Slice1 = $Array[0..2]
$Slice2 = $Array[3..5]    

Joining arrays 

Joining an array involves combining its elements into a single string, with a specified delimiter between each item. It is useful especially when you need to format the content of an array as a string, such as when creating a CSV (comma-separated value) file. 

For example, to join the elements of an array with commas as a delimiter:

$Array=@(1,2,3,4,5,6)
$Joined = $Array -Join "," 

Splitting strings into arrays

Just as you can join an array’s contents into a string, you can also split a string into an array. The operation uses a delimiter to break the string into individual elements. Here’s an example of splitting a comma-separated string into an array: 

$String"1,2,3,4,5,6"
$Array = $String -Split ","

Looping Through Arrays With ForEach()

In PowerShell, it’s common to need to perform an action on every item in an array. The simplest way to handle this is by using a ForEach loop

Suppose you have a small array of numbers and want to multiply each by 5. You could use the ForEach loop to parse the array and extract the values to be multiplied. Here is what the code looks like:

$Array=@(1,2,3,4,5,6)
ForEach ($Item in $Array)
 {
$Value = $Item * 5
$Value
}    

Why use ForEach instead of For?

You might wonder why I use a ForEach loop instead of a traditional For loop. It’s for simplicity. You must manually set the starting and ending positions in a For loop,. Since array indexing starts at 0, you would set the loop to begin at that position. You can use $Array.Length to determine the last position in the array. Here’s how that would look: 

$Array=@(1,2,3,4,5,6)
$Size=$Array.Length
For ($I=0; $I –lt $Size; $I++){
$Value = $Array[$i] * 5
$Value
}

While this technique works, the ForEach loop is often simpler because it automatically handles iterating over each element without the need to set up a counter or manually check array bounds.

Where-Object and Other Filtering Techniques

PowerShell offers many techniques to filter the contents of an array. The most common method involves using the Where-Object cmdlet. 

For instance, suppose you have a numerical array and want to filter out the number 3. You could do so by using the following code:

$Array = @(1,2,3,4,5)
$FilteredArray=$Array | Where-Object {$_ -ne 3}
$FilteredArray

In this example, the Where-Object cmdlet checks if each position within the array ($_) is not equal (-ne) to 3. Assuming this condition is met and a position holds something other than the number 3, the data from the position is added to the filtered array.

-Contains and -Ccontains

While Where-Object is often the go-to filter, there are other helpful filtering techniques in PowerShell. One such filter is -Contains. However, you must be a little careful using this one.

For example, if you have an array of colors and want to check if “blue” is in the array, you can use:

$Array=@("red","blue","green")
$Array -Contains "Blue"

The code would return True because the array contains the word “Blue.” However, it’s important to note that the -Contains operator performs a case-insensitive comparison by default. 

If you need to perform a case-sensitive comparison, use the -Ccontains instead. This comparison will only return True if the exact case matches.

$Array = @("red", "blue", "green") 
$Array -Ccontains "Blue"		# This will return False because "blue" is not the same as "Blue"

infographic highlights key points made in this article about PowerShell arrays

How To Avoid Common Pitfalls of PowerShell Arrays

Working with PowerShell arrays can lead to snags, especially for beginners. Let’s explore a few and how to avoid them.  

1. Accidentally overwriting an array 

One of the most common mistakes is accidentally overwriting an array instead of modifying it. For example, consider the following code:

$Array=@(1)
$Array=@(2)     
  • The first line creates an array and assigns it a value of 1. 

  • The second line deletes the original array and replaces it with a new array containing the value of 2. 

If you intended to append 2 to the existing array, not replace it, you must use the += operator like this:

$Array=@(1)
$Array += 2

This way, value 2 is appended to the array, not replacing it. Also notice that when appending an item, you do not need to use the @() syntax or paratheses around the value being added. 

2. Performance issues with the += operator

While the += operator is convenient when adding items to an array, you should understand its performance implications. When you use the += operator, PowerShell is essentially creating a new array every time you append an element, which can cause PowerShell to slow to a crawl for large-scale operations.

For example:

$Array=@(1)
$Array += 2			# Creates a new array every time this is run

If you add many items to an array in a loop, this repeated creation of new arrays can cause performance issues, especially with large arrays. In such cases, you are better off creating an ArrayList and using the Add method. 

Here is an example:

$ArrayList = [System.Collections.ArrayList]::New()
$ArrayList.Add($Data)		# Adds the data without recreating the array each time

PowerShell Array FAQs

Q: How do I create a multidimensional array in PowerShell?

A: There are a few different ways to create a multidimensional array in PowerShell. The easiest method is to create arrays inside of an array. For example, if you want to create an array with three rows, where each row contains three items, you can define it like this: 

$Array = @(
    @(2, 4, 5), 	# First Row
    @(8, 4, 7), 	# Second Row
    @(1, 3, 5) 		# Third Row
)    

If you want to output row 2, column 1, you could use this command:

$Array[2][1]

Remember that the first row is Row 0. Likewise, the first column is Column 0.  Hence, the command above would output the number 3.

Q: What's the best way to add or remove items from an array?

A: Adding objects to a PowerShell array is simple. You call the array’s name, use the += operator, and specify the value you want to add. For example:

$Array = @(1, 2, 3)
$Array +=4
$Array

In this code: 

  • The first command would create an array ($Array) containing the numbers 1, 2, and 3. 

  • The second line appends the number 4 to the array. 

  • The last line outputs the array, which now contains 1, 2, 3, 4.

However, removing an item is a bit more complex. Generally, instead of directly removing an item, you must reconstruct the array without the unwanted value. For example, to remove the number 3 from the array:

$Array = @(1,2,3,4,5)
$Array = $Array | Where-Object {$_ -ne 3}
$Array

Alternatively, if you need to remove an item from a specific position, you can convert the array to an ArrayList, which is more flexible for modifications. Here’s how you would remove the item at position 2 (value 3): 

$ArrayList = [System.Collections.ArrayList]@(1,2,3,4,5)
$ArrayList.RemoveAt(2)
$ArrayList

In this case, the RemoveAt method removes the item at the specified index (position 2), which is the number 3. 

Q: Can you explain how to filter arrays using PowerShell?

Filtering an array usually involves checking if it contains a particular value and then either displaying the entire array minus that value or showing only the value that matches the filter. The most common way to filter an array is by using the Where-Object cmdlet, though other filtering methods exist. 

For example, let’s say you have an array containing the numbers 1, 2, 3, 4, 5 and want to filter out the number 3. You could use the following code:

$Array = @(1,2,3,4,5)
$FilteredArray=$Array | Where-Object {$_ -ne 3}
$FilteredArray

In this code block, the $FilteredArray variable contains all the elements from $Array except for the number 3. The Where-Object {$_ -ne 3} part filters out any items where the value is equal to 3 (-ne stands for “not equal”). 

Q: How do I iterate over an array and update its elements?

A: Updating a value within an array is simply a matter of replacing the value at a specific position with a new value. For example, if you have an array containing Suppose the numbers 1, 2, 3, 4, 5 and want to replace the number 3 with 6, you can do so like this: 

$Array = @(1,2,3,4,5)
$Array[2]=6
$Array

In this case, the number 3 is at the second position (index 2 since arrays are zero-indexed) and will be replaced with 6.  

If you want to update the entire array, you can loop through all the positions and update each value. Since the first position of an array is always 0, you can start the loop at index 0 and count to the array’s length, which can be expressed as $Array.Length (assuming that the name of the array is $Array). For example, if you want to multiply each value in the array by 2 and update the array, you would use the following code:

$Array=@(1,2,3,4,5)
For ($I=0; $I –lt $Array.Length; $I++){
$Array[$i] = $Array[$I]*2
}
$Array   

About the Author

Brien Posey

Brien Posey is a bestselling technology author, a speaker, and a 20X Microsoft MVP. In addition to his ongoing work in IT, Posey has spent the last several years training as a commercial astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space.

https://brienposey.com/

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like