PowerShell Cannot Index into a Null Array – How to Fix

Are you getting an error “Cannot index into a null array” in PowerShell? If yes, this is probably you’re trying to grab something from a container that doesn’t exist (or is empty).

In this tutorial, I will explain what causes the “cannot index into a null array” error and how to fix it.

Understanding the Problem: What’s Actually Happening?

Before we fix the problem, let’s understand what’s going on. In PowerShell, when you try to access an element in an array using bracket notation like $myArray[0], PowerShell expects $myArray to be an actual array object. If it’s $null (meaning it doesn’t exist or was never initialized), you’ll get our dreaded error.

Here’s a simple example that triggers the error:

$users = $null
$firstUser = $users[0]  # Error: Cannot index into a null array

Here is the exact error, you can see in the screenshot below:

powershell cannot index into a null array

This typically happens when:

  • A command returns no results (like Get-Process looking for a non-existent process)
  • You forgot to initialize a variable
  • A function returns $null instead of an empty array
  • Data from an external source (API, file, etc.) comes back empty

Check out How to Check if a Variable is Null in PowerShell?

Now, let us check different methods to fix this issue.

Method 1: The Null Check

In PowerShell, the simplest approach is to check whether your variable is null before accessing its elements.

Basic null check:

Here is how to do a basic null check in PowerShell.

$processes = Get-Process -Name "NonExistentProcess" -ErrorAction SilentlyContinue

if ($null -ne $processes) {
    $firstProcess = $processes[0]
    Write-Host "First process: $($firstProcess.Name)"
} else {
    Write-Host "No processes found."
}

Here is the exact output in the screenshot below:

cannot index into a null array powershell

Pro Tip: Notice I wrote $null -ne $processes instead of $processes -ne $null. In PowerShell, it’s a best practice to put $null on the left side of the comparison. This prevents unexpected behavior when dealing with arrays or collections.

Array-specific check:

if ($processes -and $processes.Count -gt 0) {
    $firstProcess = $processes[0]
    Write-Host "Found $($processes.Count) processes"
}

Check out PowerShell If Null Then Empty

Method 2: The Null Coalescing Approach

If you’re using PowerShell 7.0 or later, you have access to the null coalescing operator (??), which makes your code cleaner and more readable.

$users = Get-ADUser -Filter "Name -like 'John*'" -ErrorAction SilentlyContinue
$userList = $users ?? @()  # If $users is null, use an empty array instead

$firstUser = $userList[0]  # No error! Accessing index 0 of empty array returns $null

What’s happening here? The ?? operator says “use the value on the left, but if it’s null, use the value on the right instead.” By providing an empty array @() as the fallback, we ensure we always have an array to work with.

Pro Tip: You can also use the null coalescing assignment operator (??=) to initialize variables only if they’re currently null:

$results ??= @()  # Initialize $results as empty array if it's null
$results += "New item"  # Now safe to add items

Check out Find First Match in Array and Return Value in PowerShell

Method 3: The Array Wrapper Technique — Force Everything Into an Array

Sometimes you want to guarantee that a variable is always an array, even if a command returns just one item or nothing at all. PowerShell has a clever trick for this:

# The @() wrapper forces the result to be an array
$processes = @(Get-Process -Name "powershell" -ErrorAction SilentlyContinue)

# Now $processes is ALWAYS an array, even if:
# - No processes were found (empty array)
# - Only one process was found (array with one item)
# - Multiple processes were found (array with multiple items)

if ($processes.Count -gt 0) {
    Write-Host "First process ID: $($processes[0].Id)"
} else {
    Write-Host "No PowerShell processes running"
}

Why this works: The @() syntax creates an array subexpression. If the command inside returns nothing, you get an empty array. If it returns one thing, you get a single-element array. If it returns multiple things, you get a multi-element array. You’re never left with $null.

Be careful with this approach when working with large datasets. You’re creating a new array in memory, which could impact performance if you’re dealing with thousands of objects.

Check out PowerShell Convert Byte Array to Hex String

Method 4: Try-Catch for Graceful Error Handling

For production scripts where you want comprehensive error handling, wrapping your array access in a try-catch block gives you the most control:

function Get-FirstItem {
    param($Collection)
    
    try {
        if ($null -eq $Collection) {
            throw "Collection is null"
        }
        return $Collection[0]
    }
    catch {
        Write-Warning "Could not access first item: $_"
        return $null
    }
}

# Usage
$result = Get-FirstItem -Collection $myArray
if ($result) {
    # Process the result
}

Pro Tip: In my experience, try-catch blocks are best reserved for scenarios where you’re dealing with external data sources or user input that might be unpredictable. For simple internal script logic, the earlier methods are usually sufficient and more performant.

Check out Remove the First and Last Lines from a File Using PowerShell

Method 5: Defensive Initialization — Prevent Problems at the Source

One of the best ways to avoid null array errors is to initialize your arrays properly from the start:

# Good: Initialize as empty array
$results = @()

# Good: Initialize with default values
$numbers = @(1, 2, 3)

# Risky: Uninitialized variable
$data = Get-SomeData
# If Get-SomeData returns nothing, $data is $null

# Better: Initialize with fallback
$data = Get-SomeData
if (-not $data) { $data = @() }

# Best: Use array wrapper
$data = @(Get-SomeData)

Best Practice: At the beginning of functions that build up arrays, always initialize them as empty arrays rather than leaving them undefined:

function Get-ProcessedData {
    $output = @()  # Initialize immediately
    
    foreach ($item in $InputData) {
        if (Test-Condition $item) {
            $output += $item
        }
    }
    
    return $output  # Returns empty array if no matches, never $null
}

Check out How to Read Log Files with PowerShell?

Method 6: Using the FirstOrDefault Pattern

If you’re specifically interested in just the first element (or a default if none exists), you can create a reusable pattern:

function Get-FirstOrDefault {
    param(
        [Parameter(Mandatory=$false)]
        $Collection,
        
        [Parameter(Mandatory=$false)]
        $Default = $null
    )
    
    if ($Collection -and $Collection.Count -gt 0) {
        return $Collection[0]
    }
    return $Default
}

# Usage examples
$processes = Get-Process -Name "chrome" -ErrorAction SilentlyContinue
$firstProcess = Get-FirstOrDefault -Collection $processes -Default "No process found"

$users = @(Get-ADUser -Filter "Department -eq 'IT'")
$firstUser = Get-FirstOrDefault -Collection $users

Intermediate Tip: You can extend this pattern to create Get-LastOrDefault, Get-ItemAtOrDefault, and similar helper functions that make your code more readable and less error-prone.

Check out Add an Element to the Beginning of an Array in PowerShell

When to Use Which Method?

Now, let me give you a summary of when to use which method.

  • Use null checks (if ($null -ne $var)) when you need simple validation before array access
  • Use null coalescing (??) when you’re on PowerShell 7+ and want clean, modern code
  • Use array wrappers (@()) when you need to guarantee array behavior regardless of command output
  • Use try-catch when dealing with unpredictable external data or when you need comprehensive error logging
  • Use defensive initialization when building functions that return collections—always return arrays, never null
  • Use helper functions (like FirstOrDefault) when you have repeated patterns across your codebase

I hope you now understand how to fix the PowerShell error that says: cannot index into a null array using various methods.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.