1

I have been grabbing the file data from student_data.dat and trying to display it into tabular form. The first 3 lines of the file are written like this:

Jamie Zawinski,78.8,81.0,77.3,80.0,80.0,77.0
Adam Douglas,86.2,69.0,77.8,81.0,87.5,88.0
Wallace Steven,66.2,68.0,91.3,78.6,80.3,86.4

I wish to set it up into a table with headers of Student Name, Assignment-1, Assignment-2, etc. I will later be manipulating the data to calculate the class averages for each assignment and the students overall average in the course so far. Each method of setting up the table results in the file being displayed as:

@{Name=Jamie Zawinski; Assignment-1=78.8; Assignment-2=81.0; Assignment-3=77.3; Assignment-4=80.0; 
Midterm_Exam=80.0; Final_Exam=77.0} @{Name=Adam Douglas; Assignment-1=86.2; Assignment-2=69.0; 
Assignment-3=77.8; Assignment-4=81.0; Midterm_Exam=87.5; Final_Exam=88.0} @{Name=Wallace Steven; 
Assignment-1=66.2; Assignment-2=68.0; Assignment-3=91.3; Assignment-4=78.6; Midterm_Exam=80.3; 
Final_Exam=86.4}

My coding has looked like this:

$file = Import-Csv C:\**real path**\student_data.dat -Delimiter ',' -Header 'Name', 'Assignment-1','Assignment-2','Assignment-3','Assignment-4','Midterm_Exam','Final_Exam'
Write-Host $file

I tried adding:

foreach ($line in $file){
$data += [pscustomobject]@{
    Name = $line.name
    Assignment-1 = $line.Assignment-1
    Assignment-2 = $line.Assignment-2
}
}

and writing instead:

$filedata = Get-Content ./student_data.dat
$newline = $filedata.Split("`n")
$newline.count
foreach ($l in $newline){
$Names = $l.Split(",")[0].Trim()
$Assignment-1 = $l.Split(",").Trim()
[pscustomObject]@{
Names = $Names;
Assignment-1 = $Assignment-1
}
}

but errors occurred.

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206

1 Answers1

2

First of all, note that you get a more readable output if you use Write-Output instead of Write-Host, which tries to push the entire input into a single string. (Or just remove it altogether, $file is equivalent to Write-Output $file)

As Matthias R. Jessen commented, you are probably looking for the Format-Table command:

$path = "C:\**real path**\student_data.dat"
$header = 'Name', 'Assignment-1','Assignment-2','Assignment-3','Assignment-4','Midterm_Exam','Final_Exam'
$data = Import-Csv $path -Delimiter ',' -Header $header
$data | Format-Table

Note this just "pretty-prints" the data for display in the console. The data is not changed and you should not use this for any kind of file output. And it's not really necessary for working with the data. Once you're done manipulating your data, you can just export it back as CSV:

$outpath = "C:\**real path**\student_data_result.csv"
$data | Export-Csv $outpath -Delimiter "," -NoTypeInformation
marsze
  • 15,079
  • 5
  • 45
  • 61