Export-CSV -NoTypeInformation (#PSHelp)

I ask a lot of questions about scripting online. A. LOT.  It’s probably been one of the best ways I’ve found for me to learn, and I’ve been doing it for years, mostly on Twitter or Reddit.  Recently I found that my level of coding ability in Powershell has got to the point where I’m actually now able to start answering other people questions. Generally its the simpler stuff as a good 80% of what I see is still way beyond me, but it’s a good sign of progress regardless.

Anyway, a question was posted recently using the #pshelp hashtag on Twitter.  How do you replace the header line of multiple csv files at once?

I saw this and maybe cockily thought to myself, “that’s got to be an easy 2 liner, bet I can boost my ego and quickly write out a solution”.  A good 2 hours, 1 reddit post for help, and a discussion on twitter later, I was just getting my experimental code snippets together into something workable.  Turns out this had opened up quite the hole in an a relatively “simple” task.  I won’t go into the gory details of what I tried and failed at, but here is what was left over from my experiments in the ISE window :


This is what i eventually got working :

$CSVLocation = "C:\Stuff\CSVs"
$NewHeaders = @("6","7","8", "9", "10")
$CSVs = Get-ChildItem $CSVLocation -Recurse | select -ExpandProperty name

foreach($CSV in $CSVs)
$data = Import-CSV $CSVLocation\$CSV -Header $NewHeaders
$data2 = $data[1..($data.Length)]
$data2 | Export-CSV $CSVLocation\$CSV -NoTypeInformation

This is actually quite simple. It simply sets variables for the location of the CSV files, the new header row, and grabs each of the CSV files names.  It then imports the CSV file with the additional header row (which will be positioned 2nd) and calls this $data.  $data is then converted to $data2 where it just skips the first line (ie the original header row). Finally it exports $data2 out as a CSV.  There are probably better ways of doing this, but it works well enough for me.

There we go, all in all, once I understood what was going on, this was relatively straight forward. Nice to learn something new! Hope this helps someone else one day 🙂

UPDATE: I had this post scheduled to go tomorrow but today I found out something that I thought should be tagged on to the end of this………….$PSDefaultParameterValues! Basically, Shane O’Neill mentioned this to me on Twitter today and I thought it was brilliant!  It had been mentioned that -NoTypeInformation is now default in Powershell Core and I had been wondering if there was something similar I could do outside of Core.

Turns out that all you need to do to stop having to remember to set -NoTypeInforation is this: