question

ChristopherJack-1763 avatar image
0 Votes"
ChristopherJack-1763 asked RichMatheisen-8856 commented

Add column at the start and end of a CSV in powershell

Hi,

I have the following code


 $b = Import-CSV -Path "\\server\Shared_Documents\FC Folder\Despatch\Brexit Files\Palletinfo\DHL\DHL 26-01-2021.csv" -Delimiter ","
 $b | Add-Member -MemberType NoteProperty -Name 'id' -Value $null
 $b | Add-Member -MemberType NoteProperty -Name 'Date_upload' -Value (get-date).ToString("dd-MM-yyyy")
 $b | Export-Csv "\\server\Shared_Documents\FC Folder\Despatch\Brexit Files\Palletinfo\DHL\DHL 26-01-20211.csv" -NoTypeInformation
 #$ImportFile = "\\server\Shared_Documents\FC Folder\Despatch\Brexit Files\Palletinfo\DHL "+$today+".csv"
 Write-Host –NoNewLine $b

Which add two new columns called id and date_upload.

This works, the problem is that it adds it to the end of the file. I am wanting to add id to beginning and Date_upload to the end of the column list.

How would I go about doing that? Any help appreciated.





windows-server-powershellwindows-sysinternals-pstools
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered RichMatheisen-8856 commented

I think you're looking for something like this:

 import-csv c:\junk\x.csv |
     ForEach-Object{
         $hash = [ordered]@{id=$null}
         $i = $_
         $_.psobject.properties |
             ForEach-Object{
                 $hash.($_.Name) = $i.($_.Name)
             }
         $hash.Date_Uploaded = (get-date).ToString("dd-MM-yyyy")
         [PSCustomObject]$hash
     } | Export-CSV c:\junk\x1.csv -NoTypeInformation
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for posting this. It did what I needed, at least.

It be nice if the "add-member" had a "position" field - would make this MUCH simpler, IMO.

0 Votes 0 ·

The properties you add are added to an ordered hash ($object.psobject.properties), so the order is chronological. A "normal" hash doesn't have a predictable order in its keys.

However, you can simply pipe the object into a "Select-Object" cmdlet and select the properties in any order you like, AND add additional properties using calculated properties.. Export the output of that cmdlet.

The way that I proposed doesn't require you to know the names of the columns in the imported CSV . . . so I think it's much less work (and more predictable).

0 Votes 0 ·