Here is a minimal repro example.
Expected result:
PS C:\> ("a", "b")
a
b
PS C:\> ("a", "b") | Select-String "b"
b
PS C:\>
Actual result:
PS C:\> ("a", "b")
a
b
PS C:\> ("a", "b") | Select-String "b"
b
PS C:\>
As you can see, the second output has one empty line before and two empty lines after the matched lines.
Why does that happen? And what can I do about it?
(Note: This is a minimal example. In my real code, I'm parsing svn status
output for uncommitted files and I get the same problem of spurious newlines.)
The reason for weird output is that Powershell is all about objects. In this particular case, Select-String
returns MatchInfo
object(s). Like so,
PS C:\> $o = ("a", "b") | Select-String "b"
PS C:\> $o
b
PS C:\> $o.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False MatchInfo System.Object
For extra confusion, explicit call to ToString()
doesn't output the line breaks:
PS C:\> $o.ToString()
b
PS C:\>
For a work-around, query MatchInfo's Line property like so,
PS C:\> ("a", "b") | Select-String "b" | % { $_.Line }
b
PS C:\>
Please see also Keith Hill's answer about similar a question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With