Count Rows in CSV files and export results to CSV

こ雲淡風輕ζ 提交于 2020-01-22 03:22:13

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/58306170/count-rows-in-csv-files-and-export-results-to-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!