Skip to content

PowerShell Arrays

How to create, manipulate, and optimize arrays in PowerShell using comma separation, typed arrays, indexing, slicing, and performance-efficient methods like [System.Collections.Generic.List[T]].

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:

Example of Comma Separationpowershell
$fruits = "Apple", "Banana", "Cherry"
$fruits.GetType().Name
Outputplaintext
Object[]

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:

Example of Array Subexpressionpowershell
$EmptyArray = @()

$SingleItem = @("web-node-01")
$SingleItem.Count
Outputplaintext
1

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

Example of Strongly-Typed Arrayspowershell
[int[]]$TargetPorts = 80, 443, 8080, 8443
[string[]]$HostNames = "web01", "sql01", "ad01"
$TargetPorts -join ", "
Outputplaintext
80, 443, 8080, 8443

Attempting to add an unconvertible type to a strongly-typed array triggers an immediate runtime error:

Example of Type Enforcement Failurepowershell
[int[]]$TargetPorts = 80, "InvalidPort"
Outputplaintext
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:

Example of Range Operatorpowershell
$Octets = 1..5
$Octets -join ", "
Outputplaintext
1, 2, 3, 4, 5

Indexing 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.
Example of Indexingpowershell
$Nodes = "alpha", "bravo", "charlie", "delta", "echo"

Write-Output "First element: $($Nodes[0])"
Write-Output "Last element:  $($Nodes[-1])"
Outputplaintext
First element: alpha
Last element:  echo

Array Slicing

You can extract multiple elements at once by passing a sequence of indices or an internal range using the range operator ..:

Example of Slicingpowershell
$Nodes = "alpha", "bravo", "charlie", "delta", "echo"

$Selected = $Nodes[0, 2, 4]
$Selected -join " | "

$SubArray = $Nodes[1..3]
$SubArray -join " | "
Outputplaintext
alpha | charlie | echo
bravo | charlie | delta

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

Example of Adding Elementspowershell
$fruits = @("Apple", "Banana")
$fruits += "Cherry"
$fruits -join ", "
Outputplaintext
Apple, Banana, Cherry

where += 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:

Example of Removing Elementspowershell
$Servers = "web01", "sql01", "mail01", "proxy01"

$FilteredServers = $Servers | Where-Object { $_ -ne "sql01" }
$FilteredServers -join ", "
Outputplaintext
web01, mail01, proxy01

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

Example of Jagged Arraypowershell
$Matrix = @(
    @(1, 2, 3),
    @(4, 5, 6),
    @(7, 8, 9)
)

$Matrix[1][2]
Outputplaintext
6

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

Example of Rectangular Multi-Dimensional Arraypowershell
$Grid = New-Object 'int[,]' 2, 3
$Grid[0, 0] = 100
$Grid[0, 1] = 200
$Grid[0, 2] = 300

$Grid[0, 1]
Outputplaintext
200

You can also declare a general-purpose object matrix with strings:

Example of Object Matrixpowershell
$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]
Outputplaintext
D

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

Example of Count and Lengthpowershell
$fruits = @("Apple", "Banana", "Cherry")
$fruits.Count
$fruits.Length
Outputplaintext
3
3

Sort-Object and [Array]::Sort()

Sort-Object is the pipeline-friendly way to sort without modifying the original array; [Array]::Sort() sorts in place.

Example of Sort-Objectpowershell
$numbers = @(5, 3, 1, 4, 2)
$numbers | Sort-Object
Outputplaintext
1
2
3
4
5

Reversing an Array

Example of [Array]::Reverse()powershell
$numbers = @(1, 2, 3, 4, 5)
[array]::Reverse($numbers)
$numbers
Outputplaintext
5
4
3
2
1

where [array]::Reverse() is a static .NET method that reverses the array in place.

Combined Example: Array Methods in Action

Example of Array Methodspowershell
$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:

  • .Count returns 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.
Outputplaintext
Initial Count: 4
Sorted: bits, dhcp, spooler, wuauserv
Reversed: wuauserv, spooler, dhcp, bits
Index of 'bits': 3

Practical Example: Server Pool Availability Audit

The following script manages an array of target endpoints, slices the array for processing, and outputs structured audit objects:

audit-server-pool.ps1powershell
$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")
    }
}

$Report

where:

  • $ClusterNodes initializes a string array using @(...).
  • $ClusterNodes[0..1] extracts a slice containing the first two items.
  • Test-Connection -Quiet runs an ICMP ping check returning $true or $false.
  • [PSCustomObject] wraps the result for tabular console output.

Execute the script from the console:

Consolepowershell
pwsh ./audit-server-pool.ps1
Outputplaintext
TargetNode Reachable EvaluatedAt
---------- --------- -----------
127.0.0.1       True 2026-09-27 21:30:04
localhost       True 2026-09-27 21:30:04
Navigation