How to ensure Export-Csv is in same column order?

86 views Asked by At

I have the following PowerShell code that imports a csv (that has 35 column) and modifies the "Account" column. It's working as expected. However, when I export, it's adding it as the first column when it should be the 7th position.

$Results = Import-Csv "$Env:FILEPATH\Metadata\Booking*.csv" | Select-Object @{Name = 'Account'; Expression = {@("A_"+$_."Account") -replace "[^0-9a-zA-z]",'_'}}, * -ExcludeProperty Account

# output to (new) csv file
$Results | Export-Csv -Path "$Env:FILEPATH\Metadata\Bookingtest.csv" -NoTypeInformation

Is there a way to preserve column order upon export? Thank you!

1

There are 1 answers

4
Santiago Squarzon On

Instead of creating new objects with Select-Object, update the property of the object you already have:

Import-Csv "$Env:FILEPATH\Metadata\Booking*.csv" | ForEach-Object {
    # update the property
    $_.Account = 'A_' + $_.Account -replace '[^0-9a-zA-z]', '_'
    # output the updated object
    $_
} | Export-Csv -Path "$Env:FILEPATH\Metadata\Bookingtest.csv" -NoTypeInformation

From feedback in comments, to remove quotes from your Csv in PowerShell 5.1 before exporting to a file you can use the regex pattern shown in this answer, the code would be:

$csv = Import-Csv "$Env:FILEPATH\Metadata\Booking*.csv" | ForEach-Object {
    # update the property
    $_.Account = 'A_' + $_.Account -replace '[^0-9a-zA-z]', '_'
    # output the updated object
    $_
} | ConvertTo-Csv -NoTypeInformation

$csv -replace '"([^,]*?)"(?=,|$)', '$1' |
    Set-Content -Path "$Env:FILEPATH\Metadata\Bookingtest.csv"