Sorting data in PowerShell

Viewed 44

Working in powershell I am wondering how to Sort a txt file formated like

Smith,John,45
Jean,Rob,60

The code I have listed below sorts the Last names correctly but I cannot get the average age of all the names and also when I try to get the Age sorted output it only displays some of the names. Any suggestions on how to properly get these outputs?

#Average age of Data   
$fileLines = Get-Content -Path C:\PowerShell\m22.txt   
-split '\r?\n'

$fileLines | Measure-Object { [int] $_.age } -Average | ForEach-Object Average

#Last name sorted Output  
Get-Content -Path C:\PowerShell\m22.txt | Sort-Object

#Age sorted Output  
$fileLines = Get-Content -Path C:\PowerShell\m22.txt  
-split '\r?\n'

$fileLines | Sort-Object -Descending { [int] ($_ -split ',')[-1] } 
1 Answers

The data is already comma seperated, making it ideal to use Import-Csv like this:

$csv = Import-Csv -Path 'C:\temp\m22.txt' -Delimiter ',' -Header Lastname,Firstname,Age

Note that if your file already has a line with header names you can omit the -Header parameter.

To sort the list:

# sort
$csv = $csv | Sort-Object LastName

And to get average age:

# get average age
$csv | Measure-Object -Property Age -Average
Related