2
votes

I am trying to get a list of files and a count of the number of rows in each file displayed in a table consisting of two columns, Name and Lines.

I have tried using format table but I don't think the problem is with the format of the table and more to do with my results being separate results. See below

#Get a list of files in the filepath location
$files = Get-ChildItem $filepath 

$files | ForEach-Object { $_ ; $_ | Get-Content | Measure-Object -Line}  | Format-Table Name,Lines

Expected results

Name Lines

File A 9

File B 89

Actual Results

Name Lines

File A
9
File B
89

2
you are correct - you are outputting two items. [grin] i would build a custom object in your ForEach-Object segment and output that.Lee_Dailey

2 Answers

3
votes

Another approach how to make a custom object like this: Using PowerShell's Calculated Properties:

$files | Select-Object -Property @{ N = 'Name' ; E = { $_.Name} }, 
    @{ N = 'Lines'; E = { ($_ | Get-Content | Measure-Object -Line).Lines } }
Name                      Lines
----                      -----
dotNetEnumClass.ps1         232
DotNetVersions.ps1            9
dotNETversionTable.ps1       64
2
votes

Typically you would make a custom object like this, instead of outputting two different kinds of objects.

$files | ForEach-Object { 
  $lines = $_ | Get-Content | Measure-Object -Line
  [pscustomobject]@{name = $_.name
                   lines = $lines.lines}
} 


name     lines
----     -----
rof.ps1     11
rof.ps1~     7
wai.ps1      2
wai.ps1~     1