Powershell import-csv with empty headers

I am using PowerShell. To import a separate TAB file with headers. The generated file has several empty lines "" at the end of the first line of headers. PowerShell error with error:

"The argument cannot be processed because the value of the argument" name "is invalid. Change the value of the" name "argument and run the operation again"

because the title requires a name.

I am wondering if anyone has ideas on how to manipulate a file to remove double quotes or enumerate them using "1" "2" "3" ... "10", etc.

Ideally, I would not want to modify the original file. I thought something like this

$fileContents = Get-Content -Path = $tsvFileName $firstLine = $fileContents[0].ToString().Replace('`t""',"") $fileContents[0] = $firstLine Import-Csv $fileContents -Delimiter "`t" 

But Import-Csv expects $ fileContents to become a path. Can I use it as a source?

+4
source share
4 answers

I had to handle multiple instances of this problem. Instead of using -Header and manually configuring each import instance, I wrote a more general method applicable to all of them. I cross out all instances of the "t" of the first line and save the file to open as the file name $ file_bak and import it.

 $fileContents = Get-Content -Path $tsvFileName if( ([string]$fileContents[0]).ToString().Contains('""') ) { [string]$fixedFirstLine = $fileContents[0].ToString().Replace('`t""',"") $fileContents[0] = $fixedFirstLine $tsvFileName = [string]::Format("{0}_bak",$tsvFileName $fileContents | Out-File -FilePath $tsvFileName } Import-Csv $tsvFileName -Delimiter "`t" 
+3
source

You can either provide your own headers, or ignore the first line of csv, or you can use convertfrom-csv at the end, as Kate says.

 ps> import-csv -Header a,b,c,d,e foo.csv 

Now the invalid headers in the file are just a line that you can skip.

-Oisin

+11
source

If you want to work with strings, use ConvertFrom-Csv, for example:

 PS> 'FName,LName','John,Doe','Jane,Doe' | ConvertFrom-Csv | Format-Table -Auto FName LName ----- ----- John Doe Jane Doe 
+3
source

My solution if you have many columns:

 $index=0 $ColumnsName=(Get-Content "C:\temp\yourCSCFile.csv" | select -First 1) -split ";" | %{ $index++ "Header_{0:d5}" -f $index } import-csv "C:\temp\yourCSCFile.csvv" -Header $ColumnsName 
0
source

All Articles