2

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
1
  • 9
    When you define a string, it's a single object. Get-Content returns an array of strings by default unless you pass the -Raw switch. This behavior is entirely consistent. Commented Aug 31, 2018 at 16:31

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Can you highlight the difference? (sorry, I don't notice any...)
@Starnutoditopo the difference is when setting the $Content variable using @( ), this will initiate an array object, which will make the desired 'output' consistent.

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.