Import-Csv include empty fields in end of row

879 views Asked by At

Edit

I'll conclude that Import-Csv is not ideal for incorrect formatted CSV and will use Get-Content and split. Thanks for all the answers.

Example CSV:

"SessionID","ObjectName","DatabaseName",,,,,,,,
"144","","AC"

Using Import-Csv none of the empty fields at the end will be counted - it will simply stop after "DatabaseName".

Is there any way to include the empty fields?

Edit: I simply need to count the fields and make sure there are less than X amount of them. It is not only the header that might contain empty fields but also the content. These files are often manually made and not properly formatted. Since the files also can get very large, I would prefer to not also use Get-Content and split since I'm already using Import-Csv and its properties.

2

There are 2 answers

0
AudioBubble On

As dbso suggested split and Length will help you. I was on the way to code a header routine which now is obsolete. Nevertheless here it is:

$FileIn = "Q:\test\2017-01\06\SO_41505840.csv"
$Header= (Get-Content $FileIn|select -first 1)-split(",")
"Fieldcount for $FileIn is $($Header.Length)"
for($i=0; $i -lt $Header.Length; $i++){if ($Header[$i] -eq ""){$Header[$i]="`"Column$($i+1)`""}}
$Header -Join(",")

Returning this output

Fieldcount for Q:\test\2017-01\06\SO_41505840.csv is 11
"SessionID","ObjectName","DatabaseName","Column4","Column5","Column6","Column7","Column8","Column9","Column10","Column11"
5
restless1987 On

Looks like it's missing its headers. If you would add some, it would work fine.

You could do something like

Get-Content My.CSV | Select -skip 1 | ConvertFrom-Csv -Header "SessionID","ObjectName","DatabaseName",'Whatnot1', 'Whatnot2', 'Whatnot3'