9

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.)

6
  • You can pipe that out to | Select-Object -ExpandProperty Line to get rid of the newlines but I have no idea why it adds the newlines so I'll wait for someone else to answer... Commented Jan 2, 2018 at 10:43
  • That is pure formatting artifacts. You should not depend on particular format, but should use properties to get values you need. Commented Jan 2, 2018 at 11:01
  • @PetSerAl are you saying that Select-String does a implicit version of Format-*? :O Commented Jan 2, 2018 at 11:09
  • @Shaneis No. Default Out-Default have implicit version of Format-*. Commented Jan 2, 2018 at 11:12
  • Interesting! Cheers @PetSerAl Commented Jan 2, 2018 at 11:29

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

Comments

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.