We help IT Professionals succeed at work.

PowerShell 1.0 count rows in CSV with trailing comma...

cyimxtck
cyimxtck asked
on
I am trying to get PowerShell to give me the count of rows in a csv file and if there are 1 rows or more(aside from the header), email the files.  Every csv file has a header and some have a trailing comma which is causing problems.

So in PowerShell 1.0 you cannot use the -Header() or you get this error:
Import-Csv : A parameter cannot be found that matches parameter name 'Header'.  

That pops up when I try to:
Import-Csv \\somedirectory\my.csv -Header (gc \\somedirectory\my.csv)[0].trim(",").split(",") | select -skip 1

$size1 = 0
#$size1 = $size1 + (Import-Csv \\somedirectory\my.csv).count
above fails due to the trailing comma with the famous:

Import-Csv : Cannot process argument because the value of argument "name" is invalid. Change the value of the "name" ar
gument and run the operation again.

Any help would be greatly! appreciated.

Thanks,

B
Comment
Watch Question

Top Expert 2014
Commented:
You can count lines with Get-Content.  Not quite sure what your question is.  You just want the number of lines that have a trailing comma?  Or are you interested in whether the header has a trailing comma?
I don't have easy access to PS 1.0 so I can't test, but you should be able to do something like this, which gives you the count of rows that have a trailing comma, excluding the header.
$count = (Get-Content file.csv | Select -Skip 1 | Where { $_ -match ",$" }).count

Open in new window

The Select-Object command is used to skip the header.
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
There is never a reason to stay with PS1. You can and must update to PS2. Too many restrictions are applied, and bugs contained.
Upgrading to PS2 will allow to provide header names.

Author

Commented:
I agree and want 2.0 but they won't do it yet.....thanks for the script as this ancient dinosaur has worked out in 1.0!  :)