2

I have a CSV file with no headers in which I need to add a column between the first and second column. I ultimately want to export the file with no headers to the same file name (hence why I'm using Import-CSV vs Get-Content).

Here is the script which adds the new column to the existing file:

(Import-CSV U:\To_Delete\Layer_search\WB_layers-mod.csv) | 
Select-Object *,@{Expression={'FALSE'}} |
Export-Csv U:\To_Delete\Layer_search\WB_layers-mod.csv -NoTypeInformation

This adds the a new column as a third column. In doing my googling, I could find no way to reorder the columns without having a header row, so I modified the script as follows:

(Import-CSV U:\To_Delete\Layer_search\WB_layers-mod.csv -header H1, H2)| 
Select-Object *,@{Name='H3';Expression={'FALSE'}} |
Select-Object -Property H1, H3, H2 |
Export-Csv U:\To_Delete\Layer_search\WB_layers-mod.csv -NoTypeInformation

This puts the columns in the correct order, but now I want to export the CSV without the header row I added. However, the only suggestions I'm finding are using Get-Content, Convert-to-CSV, and using Skip 1. That won't work for me because I'm only running PS3 and that option is not available until PS5, and I want to save back to the original file name, which you can't do with Get-Content.

I'm probably making this a lot harder than it needs to be, but I would appreciate any suggestions.

Thanks!

Edited to add:

For clarification, here is an example of the CSV file I am importing:

abc,1/1/2012
def,1/2/2012
ghi,1/3/2012

I want to add a column between the first and second columns:

abc,FALSE,1/1/2012
def,FALSE,1/2/2012
ghi,TRUE,1/3/2012

Hopefully this makes more sense.

1
  • 1
    For a more complete and flexible solution in powershell, please see this answer, taking a list and doing some additional magic. Commented Dec 11, 2022 at 6:24

1 Answer 1

4

I'd read Headers H1,H3 and calculate H2 to have them in the proper order directly.

(Import-CSV .\sample.csv -header H1, H3)|
  Select-Object H1,@{Name='H2';Expression={'FALSE'}},H3 |
    ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content New.csv

Sample output

"abc","FALSE","1/1/2012"
"def","FALSE","1/2/2012"
"ghi","FALSE","1/3/2012"
Sign up to request clarification or add additional context in comments.

3 Comments

This looks close to what I'm looking for. Would I be able to write this out to the same csv file name as I imported in?
Yes, as the initial Import-csv is enclosed in parentheses it is read in and you can reuse the file name in the same pipe.
I'm missing something somewhere because even though it is inserting the second column, it is deleting the third column. It is doing something funky in the Select-Object line because if I output the file right after that, the H3 column is gone.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.