1

I am used to coding in java and I am brand new to Powershell. I have a text file that contains Windows server info displayed like this.

14.0.3026.27,None,CU7,4229789,SQL Server 2017,0

14.0.3025.34,None,CU6,4101464,SQL Server 2017,0

14.0.3023.8,None,CU5,4092643,SQL Server 2017,0

I am trying to throw this info into a 2 dimensional array and want it to look like this.

[14.0.3026.27],[None],[CU7],[4229789],[SQL Server 2017],[0]

[14.0.3025.34],[None],[CU6],[4101464],[SQL Server 2017],[0]

[14.0.3023.8],[None],[CU5],[4092643],[SQL Server 2017],[0]

The code I have is giving this error message:

Cannot index into a null array. At line:9 char:9 + $array[$i][$j] = $word + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray

Here is my code:

$file = Get-Content "C:\Users\UserName\Desktop\sqlServers.txt"
$array = @(), @()
$i = 0
$j = 0
foreach ($line in $file){    
    $j=0

    foreach ($word in $line.split(",")){
        $array[$i][$j] = $word
        $j+=1
    }
    $i+=1
}

2 Answers 2

2

PowerShell (and .NET) arrays are fixed size so assigning to an element beyond the array bounds won't grow the array. Instead, let PowerShell build the arrays for you. The following will produce what you want (an array of arrays btw, not an actual 2-d array)

$result = get-content data.txt | foreach { , ($_ -split ',')}

In this code, reading the data will give you the rows, splitting the rows will give you the columns. The trick is the comma before the split operation. Without it, all of the elements would be streamed into a single flat array. The comma preserves the nested array so you get the desired array of arrays.

Sign up to request clarification or add additional context in comments.

Comments

0

As your file is comma separated (it's a CSV with a .txt extension) you could instead use Import-Csv to create the array.

You will need to manually specify headers as you example input doesn't include them.

Code with example headers:

$array = Import-Csv "C:\folder\sqlServers.txt" -Header Version,Something,CU,Number,Product,Another

You can then reference the items by index and property name:

PS > $array[0].CU
CU7

PS > $array[2].Product
SQL Server 2017

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.