How to specify column position using import-csv in PowerShell

徘徊边缘 提交于 2021-02-10 14:33:22

问题


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

回答1:


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 :-)




回答2:


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.



来源:https://stackoverflow.com/questions/65992990/how-to-specify-column-position-using-import-csv-in-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!