I have been working with PowerShell for the last 12 – 15 years. One thing I use frequently is arrays in PowerShell. As a PowerShell developer, you should know about PowerShell arrays.
In this tutorial, I will explain the PowerShell array, including its definition, syntax, examples, and more.
Arrays in PowerShell are powerful data structures that store collections of items. They can hold different types of data in a single structure.
What Is a PowerShell Array?
An array in PowerShell is a data structure that stores a collection of items. PowerShell arrays can contain different types of data in the same array.
Think of it as a shopping list or a container that can hold multiple values at once. The beauty of PowerShell arrays is that they allow you to work with groups of related items as a single unit.
Here’s how you create a simple array in PowerShell:
$fruits = @("Apple", "Banana", "Cherry")
In this example, I’ve created an array called $fruits that contains three string values. The @() syntax tells PowerShell we’re creating an array.
When you run this command, PowerShell allocates memory to store these three strings together, allowing you to perform operations on all of them at once.
The array can also contain different types, like below:
$myArray = @(1, "hello", 3.14, $true)
Create PowerShell Arrays using Different Methods
There are several ways to create arrays in PowerShell. Let me show you the most common methods to create an array in PowerShell.
Method 1: Using the Array Operator @()
The array operator is the most explicit way to define an array in PowerShell:
$states = @("California", "Texas", "Florida", "New York")
This creates a clear, defined array with specific elements. The @() syntax is unmistakable and makes your intention clear. This approach is particularly useful when you want to ensure that PowerShell treats the collection as an array, even if it contains only one item.
You can also create arrays with different data types:
$mixedArray = @("John", 42, $true, (Get-Date))
This array contains a string, a number, a boolean value, and a date object – demonstrating PowerShell’s flexibility with arrays.
Method 2: Using Comma Separation
You can also create arrays in PowerShell by simply separating values with commas:
$numbers = 1, 2, 3, 4, 5
PowerShell automatically recognizes this as an array. This method is useful when you need to define an array quickly. Behind the scenes, PowerShell still creates a proper array object, just with less syntax.
Let’s verify that this is truly an array:
$numbers.GetType().Name # Returns "Object[]" confirming it's an array
Method 3: Create an Empty Array
Sometimes, you need to start with an empty array and add items later. Here is the syntax to create an empty array in PowerShell.
$employees = @()
This creates an empty array that you can populate as your script runs. This approach is valuable when you don’t know in advance what items will go into the array, such as when collecting results from a dynamic process.
For example, you might populate it within a loop:
foreach ($server in $serverList) {
if (Test-Connection $server -Quiet) {
$employees += $server # Add responsive servers to the array
}
}
Method 4: Range Operator
The range operator (..) is incredibly useful for sequential numbers. Here’s how to use it to create an array in PowerShell.
$oneToTen = 1..10
This creates an array containing the numbers 1 through 10. The range operator is a powerful shortcut that saves you from having to manually type each number. It works for any sequential integers, including negative numbers and reverse ranges:
$countdown = 5..1 # Creates [5, 4, 3, 2, 1]
$negativeRange = -3..3 # Creates [-3, -2, -1, 0, 1, 2, 3]
Next, you should know how to access array elements in PowerShell.
Check out Read CSV into Array in PowerShell
Access Array Elements in PowerShell
Now that you know how to create arrays, let’s look at how to access the data within a TypeScript array.
Here are a few examples.
Using Index Numbers
Arrays in PowerShell are zero-indexed, meaning the first item is at position 0:
$cities = @("Chicago", "Los Angeles", "Miami", "Boston")
$cities[0] # Returns "Chicago"
$cities[2] # Returns "Miami"
This zero-based indexing is standard across many programming languages. Think of the index as the “offset” from the beginning of the array. The first element is 0 positions away from the start, the second is 1 position away, and so on.
Here is the output in the screenshot below:

If you try to access an index that doesn’t exist, PowerShell will return nothing rather than an error:
$cities[10] # Returns nothing, as this index doesn't exist
Access Multiple Elements
You can retrieve multiple elements from a TypeScript array using a range. Here is how:
$cities = @("Chicago", "Los Angeles", "Miami", "Boston")
$cities[1..3] # Returns "Los Angeles", "Miami", and "Boston"
This technique is called “slicing” and allows you to extract a portion of the array. When you use the range operator with array indices, PowerShell creates a new array containing only those elements. This is extremely useful when working with a subset of your data.
You can also use non-sequential indices:
$cities = @("Chicago", "Los Angeles", "Miami", "Boston")
$cities[0,2,3] # Returns "Chicago", "Miami", and "Boston"
Negative Index
PowerShell also supports negative indexing to access elements from the end:
$cities = @("Chicago", "Los Angeles", "Miami", "Boston")
$cities[-1] # Returns "Boston" (the last element)
$cities[-2] # Returns "Miami" (the second-to-last element)
This feature is particularly valuable when you don’t know the exact size of the array but need to access its last few elements. Negative indices count backward from the end of the array, with -1 representing the last element.
Check out Loop Through an Array in PowerShell
Modify a PowerShell Array
Let me show you how to modify an array in PowerShell. We’ll explore the different ways to add, remove, and change array elements.
Add Elements to an Array
There are several methods to add elements; here are a few with examples.
Using the += Operator
$teammates = @("John", "Sarah", "Michael")
$teammates += "Jessica"
# $teammates now contains "John", "Sarah", "Michael", "Jessica"
The += operator appends a new element to the array. What’s happening behind the scenes is important to understand: PowerShell creates a completely new array with all the original elements plus the new one, then assigns this new array back to the variable.
Pro Tip: While
+=is convenient, be aware that it creates a new array each time. For large arrays, this can impact performance.
For example, adding 1,000 items one at a time using += would create 1,000 intermediate arrays, which is inefficient. For better performance with large arrays, consider the ArrayList approach below.
Using Array Methods
Another way to add elements to an array is by using the add() method. Here is an example.
$customerIDs = [System.Collections.ArrayList]@(1001, 1002, 1003)
$customerIDs.Add(1004) # Returns the index where the item was added
Using ArrayList provides better performance for frequently modified collections. Unlike standard PowerShell arrays, ArrayList is designed for efficient additions and removals. The Add method returns the index where the item was added, which you might want to suppress in some cases:
$null = $customerIDs.Add(1005) # Suppresses the output
You can also insert an element at a specific position:
$customerIDs.Insert(1, 1500) # Inserts 1500 at index 1
# $customerIDs now contains 1001, 1500, 1002, 1003, 1004, 1005
Remove Elements from an Array
There are various techniques to remove elements from a PowerShell array.
Filter() Method
$ages = @(25, 30, 17, 42, 15)
$adults = $ages | Where-Object { $_ -ge 18 }
# $adults contains 25, 30, 42
The Where-Object cmdlet (often shortened to where) creates a new array containing only elements that match certain criteria. In this example, $_ represents each item in the array as it passes through the pipeline, and we’re keeping only values greater than or equal to 18.
Here is the exact output in the screenshot below:

Create a New Array Without Certain Elements
This is another way to remove elements.
$devices = @("iPhone", "Android", "BlackBerry", "Windows Phone")
$currentDevices = $devices | Where-Object { $_ -ne "BlackBerry" -and $_ -ne "Windows Phone" }
# $currentDevices contains "iPhone" and "Android"
This technique creates a new array by filtering out unwanted items. It’s particularly useful when you need to exclude certain values based on multiple conditions.
When working with ArrayList, you can remove items more directly:
$fruitList = [System.Collections.ArrayList]@("Apple", "Banana", "Cherry", "Date")
$fruitList.Remove("Banana") # Removes the specified item
$fruitList.RemoveAt(0) # Removes the item at index 0 (Apple)
# $fruitList now contains "Cherry", "Date"
Check out Export Arrays to CSV in PowerShell
Iterate Through Arrays in PowerShell
Arrays in PowerShell hold multiple items that you can work with. Let me show you now how to access each item in an array. PowerShell offers several ways to loop through arrays and process each element.
Using Loops
PowerShell provides multiple loop structures to iterate through arrays. The most common are foreach, for, and while loops.
The foreach loop is easy to read all the items from a PowerShell array.
$fruits = "Apple", "Banana", "Cherry"
foreach ($fruit in $fruits) {
Write-Host "Processing $fruit"
}
Here is the exact output in the screenshot below:

The for loop gives you more control with an index:
$names = "John", "Mary", "Bob"
for ($i = 0; $i < $names.Count; $i++) {
Write-Host "Name at position $i is $($names[$i])"
}
The while loop continues until a condition is met:
$numbers = 1, 2, 3, 4, 5
$index = 0
while ($index -lt $numbers.Count) {
Write-Host "Current number: $($numbers[$index])"
$index++
}
Using Foreach-Object Cmdlet
The ForEach-Object cmdlet works well in the PowerShell pipeline. It processes each item from the pipeline input.
Basic syntax for ForEach-Object:
$letters = "a", "b", "c"
$letters | ForEach-Object { Write-Host "Letter: $_" }
This cmdlet accepts script blocks with three parts: begin, process, and end:
$data = 10, 20, 30
$data | ForEach-Object -Begin { $sum = 0 } -Process { $sum += $_ } -End { "Total: $sum" }
ForEach-Object is perfect for pipeline operations. You can chain multiple commands together:
Get-ChildItem | ForEach-Object { $_.Name } | Where-Object { $_ -like "*.txt" }
This approach works well when handling large datasets since it processes one item at a time rather than loading everything into memory.
Check out Format An Array Of Objects As Table In PowerShell
PowerShell Array Properties and Methods
Arrays in PowerShell come with built-in properties and methods you can use while working.
Array Properties
Suppose you have an array like below;
$fruits = @("Apple", "Banana", "Cherry")
| Property | Description | Example |
|---|---|---|
| Count | Returns the number of elements in the array | $fruits.Count |
| Length | Same as Count, returns the number of elements | $fruits.Length |
| IsFixedSize | Returns whether the array size is fixed | $fruits.IsFixedSize |
| IsReadOnly | Returns whether the array is read-only | $fruits.IsReadOnly |
These properties provide essential information about your arrays. Here’s how you can use them.
$temperatures = @(68, 72, 75, 71, 73)
# Check if the array is empty
if ($temperatures.Count -eq 0) {
Write-Host "No temperature data available."
}
else {
Write-Host "We have $($temperatures.Count) temperature readings."
# IsFixedSize will be True for standard arrays
if ($temperatures.IsFixedSize) {
Write-Host "This is a fixed-size array. Consider using ArrayList for frequent modifications."
}
}
Array Methods
Array provides a lot of methods in PowerShell. Here are some methods that make working with arrays easier:
1. Contains() Method
$techCompanies = @("Microsoft", "Apple", "Google", "Amazon")
$techCompanies.Contains("Apple") # Returns True
$techCompanies.Contains("Facebook") # Returns False
The Contains method checks if a specific value exists in the array. It performs a case-sensitive comparison for strings and returns a boolean result. This is much cleaner than writing a loop to search for an element.
You might use it like this:
$user = "Sarah"
$authorizedUsers = @("John", "Sarah", "Michael", "David")
if ($authorizedUsers.Contains($user)) {
Write-Host "$user is authorized to access the system."
}
else {
Write-Host "$user is not authorized. Access denied."
}
You can see in the below screenshot; it is showing me the exact output:

2. IndexOf() Method
The IndexOf method returns the position of an item within an array. If the item is found, it returns the zero-based index; if not, it returns -1. This is particularly useful when you need to know not just if an item exists, but where it is in the array.
$months = @("January", "February", "March", "April")
$months.IndexOf("March") # Returns 2
$months.IndexOf("December") # Returns -1
A practical example would be finding a user’s position in a queue:
$queue = @("Alice", "Bob", "Charlie", "Diana")
$person = "Charlie"
$position = $queue.IndexOf($person)
if ($position -ge 0) {
Write-Host "$person is in position $($position + 1) in the queue."
} else {
Write-Host "$person is not in the queue."
}
3. Clone() Method
The Clone method creates a shallow copy of an array. This means the array structure itself is duplicated, but the objects inside the array are referenced rather than copied.
$original = @(1, 2, 3)
$copy = $original.Clone()
# Modifying $copy doesn't affect $original
$copy[0] = 99
Write-Host $original[0] # Still outputs 1
# But with objects, changes to properties affect both arrays
$originalComplex = @([PSCustomObject]@{Name="John"; Age=30})
$copyComplex = $originalComplex.Clone()
$copyComplex[0].Age = 31
Write-Host $originalComplex[0].Age # Outputs 31 because both reference the same object
For a true deep copy with complex objects, you’ll need additional steps:
# Deep copy using ConvertTo-Json and ConvertFrom-Json
$deepCopy = $originalComplex | ConvertTo-Json | ConvertFrom-Json
Check out Access Array of Objects in PowerShell
Sort Arrays in PowerShell
Let me show you how to sort arrays in PowerShell.
PowerShell makes sorting arrays easy; here is an example.
$unorderedNames = @("Zack", "Emily", "David", "Amanda")
$orderedNames = $unorderedNames | Sort-Object
# $orderedNames contains "Amanda", "David", "Emily", "Zack"
The Sort-Object cmdlet (often shortened to ‘sort’) arranges array elements in ascending order by default. For strings, this means alphabetical order; for numbers, numerical order.
You can also sort in descending order:
$highToLow = @(15, 42, 3, 27) | Sort-Object -Descending
# $highToLow contains 42, 27, 15, 3
For complex objects, specify which property to sort by:
$employees = @(
[PSCustomObject]@{Name="Sarah"; Department="Sales"; Salary=75000},
[PSCustomObject]@{Name="Mike"; Department="IT"; Salary=85000},
[PSCustomObject]@{Name="Jennifer"; Department="HR"; Salary=65000}
)
$sortedBySalary = $employees | Sort-Object -Property Salary
$sortedByNameDescending = $employees | Sort-Object -Property Name -Descending
Check out Filter Array of Objects in PowerShell
Filter Arrays in PowerShell
You can use filters to extract specific elements based on criteria in PowerShell.
$salesFigures = @(15000, 23000, 8000, 42000, 16000)
$highSales = $salesFigures | Where-Object { $_ -gt 20000 }
# $highSales contains 23000, 42000
The Where-Object cmdlet evaluates each element against a condition, keeping only those that return true. This is like using a sieve to separate elements based on your criteria.
For complex filtering with multiple conditions:
$serverStatus = @(
[PSCustomObject]@{Name="SVR01"; Status="Online"; Memory=8; CPU=45},
[PSCustomObject]@{Name="SVR02"; Status="Online"; Memory=16; CPU=22},
[PSCustomObject]@{Name="SVR03"; Status="Offline"; Memory=32; CPU=0},
[PSCustomObject]@{Name="SVR04"; Status="Online"; Memory=8; CPU=78}
)
# Find online servers with high CPU usage
$serversToCheck = $serverStatus | Where-Object {
$_.Status -eq "Online" -and $_.CPU -gt 70
}
# Find servers with low memory but online
$lowMemServers = $serverStatus | Where-Object {
$_.Memory -lt 16 -and $_.Status -eq "Online"
}
Check out Remove the First and Last Item in an Array in PowerShell
PowerShell Array Best Practices
After years of working with PowerShell arrays, I’ve developed some best practices that can save you time and prevent errors:
- Use descriptive variable names:
$employeesis more meaningful than$e
Clear, descriptive names make your code self-documenting and easier to maintain. For example, instead of:
$a = @("John", "Sarah", "Michael")
foreach ($x in $a) { ... }
Use:
$teamMembers = @("John", "Sarah", "Michael")
foreach ($member in $teamMembers) { ... }
- Consider performance for large arrays: Use ArrayList or List for better performance
When working with large collections that change frequently, standard arrays can cause performance issues. For better performance:
# Instead of:
$largeArray = @()
1..10000 | ForEach-Object { $largeArray += $_ } # Creates 10,000 arrays in memory!
# Use:
$efficientList = [System.Collections.Generic.List[int]]::new()
1..10000 | ForEach-Object { $efficientList.Add($_) } # Much faster
# Or even better:
$fastestList = [System.Collections.Generic.List[int]]::new(10000) # Pre-allocate capacity
1..10000 | ForEach-Object { $fastestList.Add($_) }
- Check array bounds: Always verify an index exists before accessing it
Prevent “index out of bounds” errors by validating indices:
$data = @("Apple", "Banana", "Cherry")
$index = 5
# Unsafe:
# $item = $data[$index] # Will silently return null if index doesn't exist
# Safe:
if ($index -ge 0 -and $index -lt $data.Count) {
$item = $data[$index]
Write-Host "Item found: $item"
} else {
Write-Host "Index $index is out of bounds (array size: $($data.Count))"
}
- Be mindful of types: PowerShell arrays can mix types, but this can cause unexpected behavior
While PowerShell allows mixed-type arrays, they can lead to subtle bugs. When possible, use strongly typed arrays:
# Mixed-type array (could cause issues):
$values = @("100", 200, "300")
$sum = 0
foreach ($value in $values) {
$sum += $value # "100" will be converted to a number, but might fail with other strings
}
# Strongly-typed array:
[int[]]$numericValues = @(100, 200, 300) # Ensures all values are integers
$sum = ($numericValues | Measure-Object -Sum).Sum
- Use pipeline operations: PowerShell’s pipeline (
|) makes array operations more readable
Pipeline operations are more concise and express your intent more clearly. They follow PowerShell’s design philosophy of being readable and verb-noun oriented.
# Instead of:
for ($i = 0; $i -lt $data.Count; $i++) {
$data[$i] = $data[$i] * 2
}
# Use:
$newData = $data | ForEach-Object { $_ * 2 }
- Consider array immutability: Treat arrays as immutable when possible
Instead of modifying arrays in place, create new ones with the desired changes. This approach is more predictable and easier to debug:
# Instead of modifying in place:
$names = @("John", "Sarah", "Mike")
$names[1] = "Sarah Smith"
# Create a new array with the changes:
$names = @("John", "Sarah", "Mike")
$updatedNames = $names.Clone()
$updatedNames[1] = "Sarah Smith"
I hope you learn how to work with an array in PowerShell. I have explained different methods of creating arrays in PowerShell and how to access and modify a PowerShell array.
You also learned how to iterate through arrays in PowerShell using different methods.
Finally, I have also explained a few useful array properties and methods and some best practices for using an array in PowerShell.
You may also like:
- Remove Duplicate Objects from an Array in PowerShell
- Count the Number of Objects in an Array in PowerShell
- Split an Array into Smaller Arrays in PowerShell
- Convert Multiline String to Array in PowerShell
- Loop Through an Array of Objects in PowerShell
- Sort Array Of Objects In PowerShell
- Compare Array Of Objects In PowerShell
- Get the Highest Number in an Array in PowerShell
- Get Unique Values from an Array in PowerShell
- Remove Empty Lines from an Array in PowerShell
- Check if an Array Contains a String in PowerShell
- Split Comma Separated String To Array In PowerShell
- Convert Array To Comma Separated String In PowerShell
- Get The Last Item In an Array in PowerShell
- Access First Item In an Array In PowerShell
- Replace a String in an Array Using PowerShell
- PowerShell Array of Strings

Hey! I’m Bijay Kumar, founder of SPGuides.com and a Microsoft Business Applications MVP (Power Automate, Power Apps). I launched this site in 2020 because I truly enjoy working with SharePoint, Power Platform, and SharePoint Framework (SPFx), and wanted to share that passion through step-by-step tutorials, guides, and training videos. My mission is to help you learn these technologies so you can utilize SharePoint, enhance productivity, and potentially build business solutions along the way.
Awesome Article