Akaizoku
Akaizoku

Reputation: 472

Powershell Count lines in file

Issue

Measure-Object -Line behaviour is not consistent and does not return the correct number of lines when trying to read a file.

Using .Count seems to fix this specific issue but once again it is not consistent because it does not work the same way when working with a string.

Question

How can I consistently get the correct number of lines from a text or file?

MWE

$File       = ".\test.ini"
$FileContent  = Get-Content $File
$Content =
"    # 1
    [2]
    3

    5

    [7]

    ; 9
"

$EndOfFile    = $FileContent | Measure-Object -Line
$EndOfText    = $Content | Measure-Object -Line

Write-Output "Lines from file: $($EndOfFile.Lines)"
Write-Output "Lines from text: $($EndOfText.Lines)"
Write-Output "Count from file: $($FileContent.Count)"
Write-Output "Count from text: $($Content.Count)"

Note: The content of test.ini are the exact same of the $Content variable.

Output

Lines from file: 6
Lines from text: 9
Count from file: 9
Count from text: 1

Upvotes: 2

Views: 10343

Answers (1)

Tim van Lint
Tim van Lint

Reputation: 154

It true what's @TheIncorrigible1 is saying. To do it consistent in your example, you have to do it this way:

$File       = ".\test.ini"
$FileContent  = Get-Content $File

$Content = @(
    "# 1",
    "[2]",
    "3",
    "",
    "5",
    ""
    "[7]",
    ""
    "; 9"
)

$EndOfFile    = $FileContent | Measure-Object -Line
$EndOfText    = $Content | Measure-Object -Line

Write-Output "Lines from file: $($EndOfFile.Lines)"
Write-Output "Lines from text: $($EndOfText.Lines)"
Write-Output "Count from file: $($FileContent.Count)"
Write-Output "Count from text: $($Content.Count)"

Consistent output:

Lines from file: 6
Lines from text: 6
Count from file: 9
Count from text: 9

Upvotes: 4

Related Questions