0

I am trying count the rows containing values in a bunch of CSV in a folder. I managed to get the code to count it but I can't seem to find a way to export the results to a CSV. All I got is a blank CSV.

What am I missing here?

$FOLDER_ROOT = "C:\Test\2019"
$OUTPUT_CSV = "C:\Test\2019\Count.csv"

Get-ChildItem $FOLDER_ROOT -re -in "*.csv" | ForEach-Object {
    $filestats = Get-Content $_.Fullname | Measure-Object -Line
    $linesInFile = $filestats.Lines - 1
    Write-Host "$_,$linesInFile"
} | Export-Csv -Path $OUTPUT_CSV -NoType

2 Answers 2

3

There are several issues with your code:

  • Use Get-ChildItem -Filter '*.csv' instead of Get-ChildItem -Include '*.csv'. The former is faster than the latter.

  • Write-Host most likely causes the output to go directly to the host console. I've been told that this was changed in recent versions (so that host output goes to the new information stream), but for versions at least prior to v5 it's still a reality.

  • Export-Csv expects object input, since it outputs the properties of the objects as the fields of the CSV (taking the column titles from the property names of the first object). Feeding it strings ("$_,$linesInFile") will result in a CSV that contains only a column "Length", since that is the only property of the string objects.

Use a calculated property for creating a CSV with the filename and line count of the input files:

Get-ChildItem $FOLDER_ROOT -Recurse -Filter '*.csv' |
    Select-Object Name, @{n='LineCount';e={(Get-Content $_.Fullname | Measure-Object -Line).Lines - 1}} |
    Export-Csv $OUTPUT_CSV -NoType
Sign up to request clarification or add additional context in comments.

Comments

0

Write-Host writes only to the host! Most probably you see the output into the PowerShell Console? Use Write-Output, which could be piped to Export-CSV.

1 Comment

You don't need Write-Host nor Write-Output to pipe data to Export-CSV.

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.