Measure-Object -Line
的行为不一致,并且在尝试读取文件时未返回正确的行数。
使用.Count
似乎可以解决此特定问题,但又不一致,因为在处理字符串时,它的工作方式不同。
如何始终从文本或文件中获取正确的行数?
$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)"
注意:test.ini
的内容与$Content
变量完全相同。
Lines from file: 6
Lines from text: 9
Count from file: 9
Count from text: 1
答案 0 :(得分:1)
@ TheIncorrigible1的意思是真的。要在您的示例中做到一致,您必须采用以下方式:
$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)"
一致的输出:
Lines from file: 6
Lines from text: 6
Count from file: 9
Count from text: 9