lte__
lte__

Reputation: 7576

PowerShell - Reading into variable fails with "Cannot Index" error

I'm having a problem with reading into an array from a file with PowerShell (I need to use it, bash works fine but I have to solve the problem in PS,too). So, the thing is, that the program nicely reads into the $sofor parameter, then writes out the

 Write-Host $fajl[$i].split(",")[3]

line without a problem, but when I try to read it into an array in the next row, I get an error, see below:

  Cannot index into a null array.
  At C:\Users...\PSa1.ps1:16 char:5
  +                 Write-Host $pontszam[$i]
  +                 ~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
  + FullyQualifiedErrorId : NullArray

I have no idea why it works the first time and doesn't in the second. Any idea? Would be much appreciated. See the code:

 switch ($param) 
 { 
     -v {
         $fajl = Get-Content C:\Users\freeze\Desktop\powershell\formula1.csv
         $i = 0
         while ($i -lt $fajl.length) {
             $sofor[$i] = $( ($fajl)[$i].split(",")[1]);
             Write-Host $fajl[$i].split(",")[3]
             $pontszam[$i] = $( $fajl[$i].split(",")[3]);
             Write-Host $sofor[$i]
             Write-Host $pontszam[$i]
             $i = $i + 1
        }

Upvotes: 0

Views: 91

Answers (1)

EBGreen
EBGreen

Reputation: 37740

So you are using a very Bash way of doing this (understandable since you have a working Bash solution). You are trying to work with the strings in the file (again understandable coming from Bash). Powershell was built with the concept of objects built in though so that is a much better way to handle this.

Lets start with the fact that Powershell already understands CSVs. So start by loading the CSV into memory:

$fajl = Import-CSV C:\Users\freeze\Desktop\powershell\formula1.csv

That assumes that the CSV has a header row. If it does not you can specify column names when you import it:

$fajl = Import-CSV C:\Users\freeze\Desktop\powershell\formula1.csv -Header @('H1', 'H2', 'H3', 'H4')

Just use whatever column names you want and make it match the data.

Now we can work with the CSV lines as an array of objects. So if I understand what you are trying to do a loop like this should work (I'm assuming the headers that I used in the previous bit of code. Use the right column names of course):

$sofor = @()
$pontszam = @()
foreach($row in $fajl){
    $sofor += $row.H2
    $pontszam += $row.H4
    Write-Host $row.H2
    Write-Host $row.H4
}

Just to add a little something, I suspect that your initial method wasn't working because you didn't make $sofor an array before you tried to add an array element to it. I think putting $sofor = @() before the loop might fix the issue. You will be much happier in the long run though if you start learning to work with objects in Powershell.

Upvotes: 4

Related Questions