PowerShell Array: All You Need to Know!

Arrays are a fundamental data structure in PowerShell that allows storing collections of objects and values. Learning to create, manipulate, and iterate arrays efficiently unlocks more advanced scripting capabilities. In this post, I will provide a comprehensive overview of using arrays in PowerShell. Whether you are coming from another programming language or are brand new to PowerShell, this guide will give you a solid grasp of arrays. So, let’s get started on the ultimate guide to PowerShell arrays!

Introduction to arrays in PowerShell

powershell arrays all you need to know

An array is a data structure that stores a collection of items. Arrays in PowerShell can contain items of different types of data, including integers, strings, objects, and even other arrays. An array is a useful tool for storing and manipulating data in PowerShell because it allows you to store multiple values in a single variable. Using arrays in your scripts makes them much easier to read and maintain and faster to execute. Instead of having to write long lines of code for each element within your set, you can simply use the syntax @( ) followed by the array elements, E.g., @(Element1, Element2, etc.). This allows you to easily reference all the elements within your set without having to list them individually. For example, if you need to store a list of user names or file paths, an array would be the best way to do it.

In this comprehensive guide, we will go over the basics of PowerShell arrays, learn how to create and use arrays in PowerShell, when they should be used, and how they can help make your life easier.

Creating an array in PowerShell

There are several ways to create an array in PowerShell. Here are three common methods:

Option #1: Using the @() operator:

The @() syntax is used to create an array variable in PowerShell. For example:

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

This creates an array containing the integers 1 through 5. Similarly, you can create a string array with:

$array = @("apple", "banana", "mango")

Option #2: Using the , operator:

You can also create an array by separating values with commas. For example:

$array = 1, 2, 3, 4, 5

This creates an array containing the integers 1 through 5. The comma character separates the values stored in the array, and is assigned to the variable name by the assignment operator equal sign (=).

Option #3: Using the Range() method:

The Range() method is a built-in PowerShell function that generates an array of integers within a specified range. For example:

$array = 1..5

This creates an array containing the integers 1 through 5. You can also create an array with mixed type. To create an empty array, you would use the following syntax:

$myArray = @()

Modifying elements in an array

arrays in powershell

Arrays in PowerShell can be modified by updating existing elements or adding and removing items. Here are some ways to modify array elements:

Updating elements in the Array

To modify an element in an array, you can use the array index to access the element and assign it a new value. For example:

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

This will modify the element at index 2 in the array $array from 3 to 6. Here is another example:

Update an item by index:

If you know the index of the item you want to update, you can directly set its value using PowerShell:

# Define an array
$colors = "Red", "Green", "Yellow", "black", "blue"

# Update Array Element
$colors[0] = "Cyan"

This sets the first item to “Cyan”.

Use a loop to modify items:

Let’s loop through an array and update its values.

# initialize an array
$Array = @(1,2,3,4,5)

for($i=0; $i -lt $array.Length; $i++){
  $array[$i] = $array[$i] * 2
}

Find and Update an Array Element using the IndexOf Method

In PowerShell scripting, searching for specific elements within an array is a common task. Fortunately, PowerShell provides the IndexOf method to do that. For a non-repeating item in an array, you can find its index and then update it:

#Define an array
$array = @("apple", "banana", "cherry")

#Find Index of a the specific string
$index = [array]::IndexOf($array, "banana")

#Update the array element
if ($index -ne -1) {
    $array[$index] = "mango"
}
Write-Host $array  
# Output: apple mango cherry

If you want to update all occurrences of a particular value in an array, you can use a loop:

#Define an array
$array = @("apple", "banana", "cherry", "banana")

for ($i = 0; $i -lt $array.Length; $i++) {
    if ($array[$i] -eq "apple") {
        $array[$i] = "avocado"
    }
}
Write-Host $array  
# Output: avocado banana avocado date

Updating Based on Conditional Logic:

You might want to update array items based on specific conditions: E.g. If the number is greater than 3, double it!

$numbers = @(1, 2, 3, 4, 5)
$numbers = $numbers | ForEach-Object {
    if ($_ -gt 3) {
        $_ * 2 
    } else {
        $_
    }
}
Write-Host $numbers  # Output: 1 2 3 8 10

Adding elements to an array

To add an element to an array, you can use the += operator. For example:

$array = @(1, 2, 3, 4, 5)
$array += 6

This will add item 6 to the end of the array $array. You can also use the “Add()” method to add items to an array:

$array = @()
$array.Add(1)
$array.Add(2)
$array.Add(3)

The above script shows how to append elements to an existing array. Adding multiple values to an array in one line is also possible:

#Initialize array
$array = 1, 2, 3

#Append Multiple Elements to Array
$array += 4, 5, 6
powershell array

Add an object to the array in PowerShell

Objects can be placed in the array as:

# Create an array of objects
$object1 = [pscustomobject]@{
    Name = "John"
    Age = 30
}
$object2 = [pscustomobject]@{
    Name = "Jane"
    Age = 25
}
$array = @($object1, $object2)

This creates an array of objects with different types as its elements. You can create an array with mixed-type:

# Create a mixed-type array
$array = @(1, "apple", $object1, $True)

By default, elements of the PowerShell array are of [system.object] type. You can create a strongly typed array using the type name. E.g., To create an integer array type, such as string[], long[], or int32[], use:

[int[]] $IntegerArray = 1500, 2230, 3350, 4000

To get the data type of the element, use: GetType() method. E.g., $IntegerArray[0].GetType().Name

Removing elements from an array

To remove an item from the array, you can use the Remove() method or RemoveAt() methods or ArrayList as the default System.Object[] doesn’t support removing elements. This method removes the first occurrence of the specified value from the array. For example:

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

The above script will remove element 3 from the array $array. Additionally, You can use the “RemoveAt” operator to remove items from an array at the specific index:

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

This will remove element 2 from the array.

How to delete an array in PowerShell?

Here are some ways you can delete or clear an array in PowerShell:

1. Nullifying the Array:

This is the most straightforward way to remove the reference to an array:

$array = $null

2. Use Remove-Variable:

You can also use the Remove-Variable cmdlet to remove the variable that references the array:

Remove-Variable -Name array

After running the above code, if you try to access the $array variable, PowerShell will throw an error because the variable no longer exists.

3. Clear the array:

If you want to keep the array but remove its elements, you can do so by clearing it:

$array.Clear()

Accessing Array Elements

You can use the array index to access an element in an array. The index of an element in an array is its position in the array. In Windows PowerShell, array indexes start at 0. For example:

$array = @("apple", "banana", "mango")
$element = $array[2]

In this example, $element will be assigned the value “Mango” because it is the element at index 2 in the array $array. You can access the elements of the array using their index number like this:

#Get array elements by index
$array[0]  # This would return "apple"
$array[1]  # This would return "banana"

Accessing multiple elements through

#Define an array
$Array = @(1,2,3,4,5)

#Get Elements from 0 and 1st index
$Array[0,1]

You can also slice the array using its index:

$numbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
$slice = $numbers[0..4]
Write-Host "Slice: $slice"

Output: Slice: 1 2 3 4 5

Similarly, to get the last element in the array, use :

#Define an array
$Colors = "Red", "Green", "Yellow"

$Colors[-1]

Returns: Yellow

Looping through arrays with foreach

You can also use the ForEach loop to iterate through the elements of the array. Here is an example of how to loop through each item in the array and print the elements:

#get all elements in the array
foreach ($element in $array) {
    Write-host $element
}

Looping through the elements of an array from the pipeline using ForEach-Object cmdlet also works:

$Array = @(1, 2, 3, 4, 5)
$Array | ForEach-Object {"This element is: $PSItem"}

Iterating through the items of the array can be done with the “ForEach” method as well:

#Define an array
$colors = "Red", "Green", "Yellow", "black", "blue"

#Loop through Items in the array
$colors.ForEach({ $_.Length })

Iterate through an Array using the While Loop

While the For Loop is ideal for iterating through the elements of an Array, You can also use the While Loop to do that. Here is an example:

# Define an array with filenames
$FilesToProcess = @('ProjectReport.docx', 'FinancialSummary.xlsx', 'Presentation.pptx')

# Initialize the index counter
$index = 0

# Use while loop to go through each file in the array
while ($index -lt $FilesToProcess.Length) {
    # Do some process with the file
    Write-Output "Processing file: $($FilesToProcess[$index])"

    # Increment the index to move to the next file in the array
    $index++
}

This PowerShell script block uses a while loop to iterate over an array.

Joining Arrays in PowerShell

There are built-in cmdlets and operators that can be used to perform common array operations, like sort, join, filter, etc.

To join two or more arrays in PowerShell, you use the + operator. For example, if you have two arrays called $array1 and $array2, and you want to join them into a single array called $resultArray, you would use the following syntax:

$resultArray = $array1 + $array2

You can also use the @() operator to create a new array that contains the elements of both arrays. For example, if you have two arrays called $array1 and $array2, and you want to create a new array called $resultArray that contains the elements of both arrays, you would use the following syntax:

$resultArray = @($array1, $array2)

Filtering PowerShell Arrays

To filter elements in a PowerShell array, you use the Where-Object cmdlet. For example, if you have an array called $myArray and you want to filter it to only include elements that meet a certain condition, you would use the following syntax:

#Array with Numeric values
$MyArray = @(1,2,3,4,5,6,7,8,9,10)

#Filter Array
$MyFilteredArray = $MyArray | Where-Object { $_ -gt 5 }

This will create a new array called $myFilteredArray that contains only the elements from $myArray that are greater than 5. Similarly, the other comparison operators in PS, like -EQ, -NE, -LT, -LE, also work.

Length of the array in PowerShell

To get the array length in PowerShell, you can use the Length property or the Count property. For example, to get the number of elements in an array of integers, you can use either of the following approaches:

$array = @(1, 2, 3, 4, 5)
$length = $array.Length
$count = $array.Count

This gets you the size of the array!

Sort Array in PowerShell

To sort an array, use the Sort-Object cmdlet. Consider the following example:

$array = @(5, 2, 4, 1, 3)
$sortedArray = $array | Sort-Object

This will sort the array in ascending order. Similarly, to sort an array in descending order, use the -Descending switch.

$array = @(1, 3, 5, 2, 4)
$SortedArray = $array | Sort-Object -Descending
$SortedArray

The Sort-Object cmdlet doesn’t change the original array, but it returns a new sorted array!

PowerShell to split a string into an Array

To split a string into an array in PowerShell, you can use the Split() method. The Split() method takes a delimiter as an argument and returns an array of substrings delimited by the specified delimiter.

For example, to split a string on the comma character, you can use the following code:

$string = "1,2,3,4,5"
$array = $string.Split(",")

This PowerShell splits comma-separated strings into arrays.

Replace a Value in the Array

If you want to replace a value in an array, there are multiple ways to achieve this. Here are some:

#Define an array
$Colors = "Red", "Green", "Yellow"

#Replace a Value in the Array
$Colors = $Colors -replace "Yellow","Black"

You can replace an element in an array by finding its index and substituting a new value, too. Here is how:

$array = @("apple", "banana", "cherry")
$index = [array]::IndexOf($array, "banana")
if ($index -ne -1) {
    $array[$index] = "blackberry"
}

You can use a loop structure to replace all occurrences of a given value, as discussed earlier in this article.

Convert an array to a string in PowerShell

To convert an array to a string in PowerShell, you can use the -join operator. This operator takes an array as input and returns a string that consists of the elements of the array joined together using the specified delimiter.

For example, to convert an array of integers to a string, separated by commas, you can use the following code:

$array = 1, 2, 3, 4, 5
$string = $array -join ";"

This would result in $string being set to the string "1;2;3;4;5". The join operator is extremely useful when working with arrays.

Check if an array contains an element in the PowerShell

To check if an array contains a specific value in PowerShell, you can use the Contains method. Here’s an example:

$array = 1, 2, 3, 4, 5
If ($array.Contains(3)) {
    Write-host "The array contains the value 3" -f Green
}
Else {
    Write-host "The array doesn't contains the value 3" -f Yellow
}

Please keep in mind that the Contains method is case-sensitive, so if you are checking for a string value, you need to make sure that the case matches. Alternatively, you can use the -contains operator like this:

$array = 1, 2, 3, 4, 5

if ($array -contains 3) {
    Write-Output "The array contains the value 3."
}

The -contains operator is case-insensitive. You can also use the -in operator to check if an array contains a specific value:

$array = "Apple", "Orange", "Cherry"

If ("Apple" -in $array){
    Write-host "The array contains the value 'Apple'" -f Green
}
Else {
    Write-host "The array does't contain the value 'Apple'" -f Yellow
}
Array in PowerShell

Multi-dimensional Array in PowerShell

Multidimensional arrays or Nested Arrays are arrays of arrays, which allow you to store data in a tabular form. Although they aren’t as commonly used in PowerShell as they are in languages like C# or Java, they can still be beneficial in certain scenarios. Let’s walk through real-world examples to showcase the utility of multi-dimensional arrays in PowerShell.

Here is a simple example for creating multidimensional arrays and basic usage:

#Create a Multidimentional Array
$MultiArray = @(@(1, 2, 3), @(4, 5, 6), @(7, 8, 9))

# access the elements using row and column indices
$value = $multiArray[1][1] # Retrieves the value 4

To enumerate a multidimensional array, you can use nested ForEach loops:

ForEach ($Row in $MultiArray) {
    ForEach ($Item in $Row) {
        Write-Host $Item
    }
}

Let’s take a real-world example: store configuration data for different environments using a Multi-dimensional array.

# Initialize the array
$environments = @(@( "dev", "localhost", 8080 ),
                  @( "staging", "staging.example.com", 80 ),
                  @( "prod", "www.example.com", 443 ))

# Loop through each environment to print details
foreach ($env in $environments) {
    Write-Host "Environment: $($env[0]), Domain: $($env[1]), Port: $($env[2])"
}

For more information on PowerShell Arrays, refer to: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arrays?view=powershell-7.3

Arrays vs. Other Data Structures

Alternatives like arraylists and hashtables also store collections:

  • Arraylists (arraylist) – Resizable arrays
  • Hashtables (@{}) – Key-value pairs

Knowing the strengths of each data structure helps you choose the right collection type and decide when you should use PowerShell Arrays.

Wrapping Up

Using arrays in your PowerShell scripts is an efficient way to simplify complex operations and make them easier for others (and yourself) to understand and maintain over time. By referencing all the elements within a set with just one command instead of listing them out individually, you save both time and effort while still getting the same result! So next time you’re writing a script that requires accessing multiple elements within a set simultaneously, consider using an array instead! It just might save you some valuable time in the long run!

Can I add elements of different data types to a PowerShell array?

Yes, you can add elements of different data types to a PowerShell array. However, it is best practice to declare your array with a specific data type.

How do I compare two arrays in PowerShell?

In PowerShell, you can compare two arrays using the Compare-Object cmdlet. This cmdlet allows you to compare the contents of two arrays and identify the differences between them.
$array1 = 1, 2, 3, 4, 5
$array2 = 4, 5, 6, 7, 8
$diff = Compare-Object -ReferenceObject $array1 -DifferenceObject $array2
$diff

More here: How to use Compare-Object cmdlet in PowerShell?

How do I iterate an array in PowerShell?

You can iterate over an array in PowerShell using the “ForEach” loop. Here’s a simple example:
$array = "element1", "element2", "element3"
foreach ($element in $array) {
Write-Host $element
}

How do you select the first item in an array in PowerShell?

To select the first item in an array in PowerShell, you can use the index notation [0]. For example, if your array is named $myArray, you can access the first item using $myArray[0].

How to pass an array as a parameter in PowerShell?

To pass an array as a parameter in PowerShell, you can use the [array] type accelerator. For example, you can define a function with a parameter that accepts an array like this: “function MyFunction([array]$myArray) { … }”. Then, when calling the function, you can pass an array as the argument like this: “MyFunction $myArray”. Here is an example:
Function Process-Array([array]$arr) {
$arr | ForEach-Object { Write-Host $_ }
}
Process-Array (1, 2, 3, 4, 5)

How to convert an array to a string in PowerShell?

To convert an array to a string in PowerShell, you can use the -join operator. Here’s an example:
$array = "element1", "element2", "element3"
$string = $array -join ", "
Write-Host $string

How do you access specific elements in an array?

To access specific elements in an array, you can use the index number of the element. As in most programming languages, arrays are zero-indexed, meaning the first element is at index 0, the second element is at index 1, and so on. You can access an element by using the array name followed by the index number in square brackets. For example, if you have an array called “myArray” and you want to access the third element, you would use “myArray[2]”.

What is @{} in PowerShell?

@{} is a hashtable in PowerShell. It is used to create an empty hashtable, which is a collection of key-value pairs. Hashtables are useful for storing and retrieving data in PowerShell scripts.

How do you clear an array in PowerShell?

To clear an array in PowerShell, you simply assign an empty array to the variable representing the array. Here is a short example:
$array = @()

How to get the last element of an array in PowerShell?

To get the last element of an array in PowerShell, you can use the index -1. The index -1 refers to the last element, -2 refers to the second last element, and so on. Here’s an example:
$array = 1, 2, 3, 4, 5
$lastElement = $array[-1]
Write-Host $lastElement

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *