Question

I am trying to remove columns from a lot of CSVs at once with Powershell. I'm trying to use

Get Child-Item *.csv | Foreach-Object {Import-Csv $_ | select data, close | Export-Csv $_ - NoTypeInformation}

However, I just end up with a bunch of empty CSVs. I'm guessing this has something to do with exporting a CSV of the same name as what I'm importing because it works fine if I use different names (i.e. Import-Csv X.csv ... Export-Csv XXXXXX.csv).

However, I couldn't figure out how to edit the output CSV names either when I have the '$_' involved and there is too many to do manually.

What is wrong with the command I am giving? Also, for future reference, how would I have the output be a different file name?

Thank you.

Was it helpful?

Solution

OK, one liners are great and all but if you start having issues it might be time to break it down. This will import it to a variable, then select the two columns that you want and export it to a file with -trimmed tacked on the end of the file name.

Gci *.csv ¦ select -expand Fullname ¦ %{
    $current = import-csv $_
    $newname = $_ -replace ".Csv$", "-trimmed.csv"
    $current ¦ select data, close ¦ export-csv $newname -notype

}

That should work, though I am unable to test since I'm posting from my phone while riding the bus on my commute home from work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top