Skip to content

/errors/powershell/cannot-index-into-a-null-array

PowerShell: Cannot index into a null array.

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated
tool
PowerShell
exit code
1
versions
Windows PowerShell 5.1, PowerShell 7.x
os
windows, linux, macos

Cannot index into a null array. means the expression before [...] is $null. PowerShell lets you read $null and properties of $null without error, but indexing it fails. Find out why the variable is empty: usually a command that found nothing, or a typo in the variable or property name. Wrapping the result in @() makes it an empty array, so [0] returns $null instead of failing.

Reproduce it

powershell
$ErrorActionPreference = 'Stop'
$files = Get-ChildItem -Filter *.nomatch
try { $files[0] } catch { $_.Exception.Message; '  -> ' + $_.FullyQualifiedErrorId }
"@() result count: $(@(Get-ChildItem -Filter *.nomatch).Count)"
"first of @(): [$(@(Get-ChildItem -Filter *.nomatch)[0])]"
'a.txt', 'b.txt' | ForEach-Object { Set-Content $_ 'x' }
(Get-ChildItem -Filter *.txt | Sort-Object Name)[0].Name

Output

Cannot index into a null array.
  -> NullArray
@() result count: 0
first of @(): []
a.txt

One result is not an array either

A command that returns one object returns the object itself, not a one-element array. $result[0] then indexes into that object (a string's first character, for example) instead of returning it. @() fixes both cases:

powershell
'only.log' | ForEach-Object { Set-Content $_ 'x' }
$one = Get-ChildItem -Filter *.log
"type without @(): $($one.GetType().Name)"
"type with @():    $(@(Get-ChildItem -Filter *.log).GetType().Name)"
"string index: $('hello'[0])"

Output

type without @(): FileInfo
type with @():    Object[]
string index: h

Safer patterns

Instead ofUse
$x = Get-Thing; $x[0]$x = @(Get-Thing); if ($x.Count) { $x[0] }
(Get-ChildItem *.log)[0]Get-ChildItem *.log | Select-Object -First 1
$text -match 'id=(\d+)'; $Matches[1]if ($text -match 'id=(\d+)') { $Matches[1] }
$hash[$key] on an undefined $hash$hash = @{} first

Sources