Ritthisha S
Ritthisha S

Reputation: 123

How to specify column position using import-csv in PowerShell

As I have many csv files and want to sort first column of csv file, in that case first column name may differ for each file. Hence how to specify the column position for sort the many different files. here is my script that I tried and am seeking like this code.($_.1)

$InputFilePath = "C\test.csv"
$OutputFolderPath ="C:\output.csv"
$UniqueValue = Import-Csv $InputFilePath  | Sort-Object -Property $_.1 | Export-Csv -Encoding Default -NoTypeInformation $OutputFolderPath

Upvotes: 2

Views: 896

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174545

Two ways:

Reflecting against psobject on each item

Import-Csv $InputFilePath |Sort-Object -Property { $_.psobject.Properties.Value[0] }

Here, we reference the hidden psobject memberset on each object to "discover" it's properties, and resolving the value of the first one.

Extracting from the first row

$data = Import-Csv $InputFilePath
$sortKey = $data[0].psobject.Properties.Name[0]

$data |Sort-Object -Property $sortKey

Here we load all the data into a variable first, then discover the first property name of the very first object in the collection, and then use that property name to pass to Sort-Object

You may find this approach performs slightly better for medium-sized files (thousands of rows), but might allocate more memory as file size increases.

Test each against your data set and see what works best :-)

Upvotes: 4

AdminOfThings
AdminOfThings

Reputation: 25001

You may do the following:

$InputFilePath = "C\test.csv"
$OutputFolderPath ="C:\output.csv"

Import-Csv $InputFilePath  | Sort-Object { $_.psobject.Properties.Value[0] } |
    Export-Csv -Encoding Default -NoTypeInformation $OutputFolderPath

Each object has a hidden psobject property, which is a type PSMemberSet. Its Properties property contains all the properties on your custom object in the order that they were deserialized. Since you want the first column's data for sorting, you can simply access its Value property. The first property will be index [0] of course.

Upvotes: 4

Related Questions