Remove Columns from CSV File Using Powershell


I need to remove several columns from a CSV file without importing the CSV file in Powershell. Below is an example of my input CSV and what I hope the output CSV can look like.











I have tried doing this the following code, but it is giving me plenty of errors and saying that I cannot use the “Delete” method this way (which I have done in the past)…Any ideas?


I am just going to add this anyway since I hope to convince you how easy it will be to avoid having to use Excel.

We assign arbitrary headers to the object and that way we can call the 1st, 4th and 6th columns by position. Once exported the file will have the following contents which match what I think you want and not what you had in the question. Your last line had an extra value (20) on it which I don’t know if it was on purpose or not.

If this is not viable I am really interested as to why.

Excel Approach

Alright, so the file is enormous so Import-CSV is not a viable option. Keeping with your excel idea I came up with this. What it will do is take column indexes and delete any column that is not in those indices.

Wait you say?… that wont work since the column indexes change as you remove columns. Using the indices we want to keep we get the inverse to delete based on the UsedRows of the sheet. We then take each of those columns to delete and remove a value equal to is array position. Reason being is that when a column is actually deleted the next value has already been adjusted to account for the shift.

I was having issues with Excel remaining open even after reading up on the “correct” way to do it. The inner logic is what is important. Don’t forget to change your paths as needed.


Remove Columns from CSV File Using Powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply