PowerShell从文本文件导入数据到二维数组时遇空数组索引错误求助
Hey there! Since you're coming from Java and new to PowerShell, let's break down why you're hitting that error and get your CSV-like text file into a proper 2D array.
Why the Error Happens
Your initial code has two key issues:
- Incorrect array initialization:
$array = @(), @()creates an array that contains two empty sub-arrays. When your loop reaches the 3rd line ($i=2),$array[$i]doesn't exist—it'snull, hence the "Cannot index into a null array" error. - Fixed-size array limitation: Even for the first two lines, PowerShell's standard arrays are fixed-size. You can't directly assign to
$array[$i][$j]because the sub-array is empty and has no slot at index$jyet.
Correct Ways to Create the 2D Array
Method 1: Simple Fixed-Size Array (Good for Small Files)
This approach builds the 2D array by adding each split row as a single element to the main array:
# Read the file content $file = Get-Content "C:\Users\UserName\Desktop\sqlServers.txt" # Initialize an empty main array $array = @() foreach ($line in $file) { # Split the line into a string array $row = $line.Split(",") # Add the row to the main array (the leading comma ensures it's added as a single sub-array) $array += ,$row } # Test accessing elements Write-Host "First row, second element: $($array[0][1])"
Note the leading comma ,$row—this tells PowerShell to add the entire row array as one element instead of expanding its elements into the main array (which would turn it into a 1D array).
Method 2: Dynamic ArrayList (Better for Large Files)
If you're working with a large file, ArrayList is more efficient than using += (which recreates the entire array each time):
$file = Get-Content "C:\Users\UserName\Desktop\sqlServers.txt" # Initialize a dynamic array list $array = New-Object System.Collections.ArrayList foreach ($line in $file) { $row = $line.Split(",") # Add the row to the list ( [void] suppresses the index number output from Add() ) [void]$array.Add($row) } # Test accessing elements Write-Host "Third row, fourth element: $($array[2][3])"
Bonus: Use PowerShell's Built-in CSV Support
If you later want to work with this data as structured objects (similar to Java POJOs) instead of a raw 2D array, PowerShell's Import-Csv cmdlet is perfect:
# Define headers for your data columns $headers = "Version", "ReservedValue", "CU", "BuildNumber", "Edition", "Flag" # Import the file as a collection of objects $sqlServerObjects = Import-Csv "C:\Users\UserName\Desktop\sqlServers.txt" -Header $headers # Access properties like objects Write-Host "First entry's edition: $($sqlServerObjects[0].Edition)"
内容的提问来源于stack exchange,提问作者Brenden Laible

