Search code examples
powershellcalculated-property

Powershell to output a list of records in a txt file


Running the following in powershell

$files = Get-ChildItem -path "C:\temp" -Recurse -Include "*.csv" 

ForEach($BusinessFile in $BusinessFiles)
{
$bfiles = get-content $BusinessFile.fullname | Measure-Object -line
$bRowsinFile = $bfiles.lines -1

write-host  "Business File Name: " $BusinessFile.name 
Write-host "Number of Rows: " $bRowsinFile -ForegroundColor Yellow 
} 

$records =@{
"File Name" = $businessFile.Name
"Number of Rows" = $bRowsinFile
}
} 

$listofFiles = @()
$listofFiles += New-Object -TypeName PSObject -Property $records

$listofFiles | Out-File "c:\test\output.txt"
Invoke-Item "c:\test\output.txt"

Powershell based on the write-host command is working properly. It gives each CSV file name along with # of rows on each file

Output issue: I only see the first file name in the output.txt file

Output shows: File name and # rows for the first file only

Goal: Is it possible for the output.txt to list all file names with the corresponding # of rows possible

Thanks


Solution

  • Similar to mklement0's answer, but I think I'd just add the information to the existing file info you're already getting.

    $listOfFiles = Get-ChildItem C:\temp -Recurse -Filter *.csv | Select-Object *,@{l='Number of Rows';e={(Get-Content $_.FullName | Measure-Object -Line).Lines - 1}}
    $listOfFiles | Select Name,'Number of Rows' | Export-Csv 'c:\test\output.csv' -NoTypeInformation