4

I'm using PowerShell To import a TAB separated file with headers. The generated file has a few empty strings "" on the end of first line of headers. PowerShell fails with an error:

"Cannot process argument because the value of argument "name" is invalid. Change the value of the "name" argument and run the operation again"

because the header's require a name.

I'm wondering if anyone has any ideas on how to manipulate the file to either remove the double quotes or enumerate them with a "1" "2" "3" ... "10" etc.

Ideally I would like to not modify my original file. I was thinking 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 is expecting $fileContents to be a path. Can I get it to use Content as a source?

4 Answers 4

11

You can either provide your own headers and ignore the first line of the csv, or you can use convertfrom-csv on the end like Keith says.

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

Now the invalid headers in the file is just a row that you can skip.

-Oisin

Sign up to request clarification or add additional context in comments.

Comments

3

If you want to work with strings instead use ConvertFrom-Csv e.g.:

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

FName LName
----- -----
John  Doe
Jane  Doe

Comments

3

I ended up needing to handle multiple instances of this issue. Rather than use the -Header and manually setting up each import instance I wrote a more generic method to apply to all of them. I cull out all of the `t"" instances of the first line and save the file to open as a $filename + _bak and import that one.

$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"

Comments

1

My Solution if you have much 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.