PowerShell Array: All You Need to Know!

Introduction to arrays in PowerShell

An array is a data structure that stores a collection of items. In PowerShell, an array can contain items of different data types, including integers, strings, and objects. 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, when they should be used, and how they can help make your life easier. Let’s get started!

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 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.

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 create an array with mixed-type:

Modifying elements in an 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.

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 the element 6 to the end of the array $array. You can also use the “Add()” method to add an element to the array:

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

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

#Initialize array
$array = 1, 2, 3

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

Add object to 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 data types as its elements. You can create an array with mixed-type:

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

PowerShell to split string into 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 string into array.

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".

Removing elements from an array

To remove an element from an 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)

This will remove the element 3 from the array $array. You can also use the “RemoveAt” operator to remove an element at the specific index from an array:

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

This will remove the element 2 from the array.

Accessing elements in an array

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 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"

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

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

Length of the array in PowerShell

To get the length of an array 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

Sort Array

To sort an array, use the Sort-Object cmdlet:

$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

Filter Array in PowerShell

To filter an array, use the Where-Object cmdlet:

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

This will create a new array containing only the elements of the original array that are greater than 3.

Check if an array contains an element in 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 in-sensitive. 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
}

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!

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

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