An array is an ordered, zero-indexed collection of items stored as a single variable. Under the hood, PowerShell arrays are built on the .NET System.Object[] class, allowing them to store elements of uniform or mixed data types: primitives, strings, or complex administrative objects.
The most common operations on arrays in PowerShell are explained below.
Creating Arrays
PowerShell provides several mechanisms to create arrays, ranging from implicit comma separation to strongly-typed declarations.
1. Comma Separation
Placing a comma between values implicitly constructs an array:
$fruits = "Apple", "Banana", "Cherry"
$fruits.GetType().NameObject[]2. Array Subexpression @()
The array subexpression operator @() explicitly ensures that an expression is treated as an array, even if it returns zero elements or a single scalar object:
$EmptyArray = @()
$SingleItem = @("web-node-01")
$SingleItem.Count13. Strongly-Typed Arrays
By default, PowerShell arrays hold items of type [Object]. To enforce that all elements match a specific type, prefix the declaration with a typed array accelerator:
[int[]]$TargetPorts = 80, 443, 8080, 8443
[string[]]$HostNames = "web01", "sql01", "ad01"
$TargetPorts -join ", "80, 443, 8080, 8443Attempting to add an unconvertible type to a strongly-typed array triggers an immediate runtime error:
[int[]]$TargetPorts = 80, "InvalidPort"MetadataError: Cannot convert value "InvalidPort" to type "System.Int32". Error: "The input string 'InvalidPort' was not in a correct format."4. Range Operator (..)
The range operator (..) generates a sequential integer array:
$Octets = 1..5
$Octets -join ", "1, 2, 3, 4, 5Indexing and Slicing
Array elements are accessed using zero-based index notation with square brackets [ ].
Zero-Based and Negative Indexing
$Array[0]: Retrieves the first element.$Array[-1]: Retrieves the last element using negative offset indexing.$Array[-2]: Retrieves the second to last element.
$Nodes = "alpha", "bravo", "charlie", "delta", "echo"
Write-Output "First element: $($Nodes[0])"
Write-Output "Last element: $($Nodes[-1])"First element: alpha
Last element: echoArray Slicing
You can extract multiple elements at once by passing a sequence of indices or an internal range using the range operator ..:
$Nodes = "alpha", "bravo", "charlie", "delta", "echo"
$Selected = $Nodes[0, 2, 4]
$Selected -join " | "
$SubArray = $Nodes[1..3]
$SubArray -join " | "alpha | charlie | echo
bravo | charlie | deltaAdding and Removing Elements
Standard .NET arrays (System.Object[]) have a fixed size once allocated in memory.
Adding Elements with the += Operator
When you append an item to an array using +=, PowerShell does not expand the original memory allocation. Instead, it creates an entirely new array in memory containing the original values plus the new element, and discards the previous array.
$fruits = @("Apple", "Banana")
$fruits += "Cherry"
$fruits -join ", "Apple, Banana, Cherrywhere += appends a new element by creating a new array combining the original elements with the added value.
Removing Elements
Because native arrays have fixed lengths, elements cannot be deleted directly via an in-place method like .Remove(). To remove items, filter them using Where-Object:
$Servers = "web01", "sql01", "mail01", "proxy01"
$FilteredServers = $Servers | Where-Object { $_ -ne "sql01" }
$FilteredServers -join ", "web01, mail01, proxy01Multi-Dimensional and Jagged Arrays
PowerShell supports both jagged arrays (arrays of arrays) and true multi-dimensional rectangular arrays.
Jagged Arrays (Arrays of Arrays)
A jagged array is an array whose elements are themselves independent arrays. Elements are accessed using consecutive bracket pairs: $Array[row][col].
$Matrix = @(
@(1, 2, 3),
@(4, 5, 6),
@(7, 8, 9)
)
$Matrix[1][2]6Rectangular Multi-Dimensional Arrays
Rectangular arrays have fixed rows and columns allocated as a continuous block. They are instantiated using the .NET type constructor New-Object 'Type[,]' rows, cols and indexed with a single bracket pair: $Array[row, col].
$Grid = New-Object 'int[,]' 2, 3
$Grid[0, 0] = 100
$Grid[0, 1] = 200
$Grid[0, 2] = 300
$Grid[0, 1]200You can also declare a general-purpose object matrix with strings:
$matrix = New-Object 'object[,]' 2, 2
$matrix[0,0] = "A"
$matrix[0,1] = "B"
$matrix[1,0] = "C"
$matrix[1,1] = "D"
$matrix[1,1]DArray Properties and Methods
Every array inherits properties and static methods from the .NET System.Array base class.
| Member | Type | Description |
|---|---|---|
.Count / .Length |
Property | Returns the total number of elements in the array. |
[Array]::Sort($arr) |
Static Method | Sorts array elements in-place in ascending order. |
[Array]::Reverse($arr) |
Static Method | Inverts the order of the array elements in-place. |
[Array]::IndexOf($arr, val) |
Static Method | Returns the zero-based index of the first occurrence of an item. |
[Array]::Clear($arr, idx, len) |
Static Method | Resets a range of elements back to their default values (0 or $null). |
.Count and .Length
Both return the number of elements in the array and can be used interchangeably.
$fruits = @("Apple", "Banana", "Cherry")
$fruits.Count
$fruits.Length3
3Sort-Object and [Array]::Sort()
Sort-Object is the pipeline-friendly way to sort without modifying the original array; [Array]::Sort() sorts in place.
$numbers = @(5, 3, 1, 4, 2)
$numbers | Sort-Object1
2
3
4
5Reversing an Array
$numbers = @(1, 2, 3, 4, 5)
[array]::Reverse($numbers)
$numbers5
4
3
2
1where [array]::Reverse() is a static .NET method that reverses the array in place.
Combined Example: Array Methods in Action
$Services = "wuauserv", "bits", "spooler", "dhcp"
Write-Output "Initial Count: $($Services.Count)"
[Array]::Sort($Services)
Write-Output "Sorted: $($Services -join ', ')"
[Array]::Reverse($Services)
Write-Output "Reversed: $($Services -join ', ')"
$TargetIndex = [Array]::IndexOf($Services, "bits")
Write-Output "Index of 'bits': $TargetIndex"where:
.Countreturns the element count.[Array]::Sort()rearranges the original array values.[Array]::Reverse()reverses the elements in-place.[Array]::IndexOf()scans the collection and returns the matching index offset.
Initial Count: 4
Sorted: bits, dhcp, spooler, wuauserv
Reversed: wuauserv, spooler, dhcp, bits
Index of 'bits': 3Practical Example: Server Pool Availability Audit
The following script manages an array of target endpoints, slices the array for processing, and outputs structured audit objects:
$ClusterNodes = @(
"127.0.0.1",
"localhost",
"10.0.0.1",
"192.168.1.1"
)
$ActiveBatch = $ClusterNodes[0..1]
$Report = foreach ($Node in $ActiveBatch) {
$PingTest = Test-Connection -TargetName $Node -Count 1 -Quiet
[PSCustomObject]@{
TargetNode = $Node
Reachable = $PingTest
EvaluatedAt = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
}
}
$Reportwhere:
$ClusterNodesinitializes a string array using@(...).$ClusterNodes[0..1]extracts a slice containing the first two items.Test-Connection -Quietruns an ICMP ping check returning$trueor$false.[PSCustomObject]wraps the result for tabular console output.
Execute the script from the console:
pwsh ./audit-server-pool.ps1TargetNode Reachable EvaluatedAt
---------- --------- -----------
127.0.0.1 True 2026-09-27 21:30:04
localhost True 2026-09-27 21:30:04