Case of failing Select-String

Usually when I need to select some lines from a text, I use -match operator. It's easy and it fills $matches variable for free when you pass scalar value in.

Today I wanted to use Select-String because of its ability to show me the context (several lines around). So I copied some text from email to clipboard and tried:

[0] Select-String -InputObject ((clip) -split "`r`n") -Pattern 'Runspace' -Context 2
> $PsHome  Evaluates to the full path of the installation directory 
for Windows PowerShell. Sample outputs:  C:\Windows\system32\ WindowsP
owerShell\v1.0\  C:\Windows\SysWOW64\WindowsPowerShell\v1.0\  Note tha
t even if you have PowerShell version 2, the dir path is still “v1.0”,
 because PowerShell 2 is meant to be compatible with version 1. $Host  
 Eval to a object that represents the.....

Garbage! Wow? Where does it come from? Ok, I'll try to pipe it.

[1] (clip) -split "`r`n" | Select-String -Pattern 'Runspace' -Context 2
  CurrentUICulture : en-US
  PrivateData      :
> IsRunspacePushed : False
> Runspace         : System.Management.Automation.Runspaces.LocalRunspace

  If you are running PowerShell in Windows Console or emacs, the name line may be:

Hmm, that's exactly what I expected. So, where is the problem?
I'll make the story short. Parameter -InputObject is of type PsObject. After looking through Reflector to the code, I found this line:

operandString = (string) LanguagePrimitives.ConvertTo(
                                operand, 
                                typeof(string), 
                                CultureInfo.InvariantCulture);

This code will be executed in method doMatch of class SelectStringCommand. The only possibility how to convert array of strings to one string is to join them (probably via $ofs) and that's exactly what happened.

IMO that's a bug. I would expect it is possible to pass object via pipeline or via parameter and the cmdlet should behave the same. Going to connect to create one.

Bug reported: You can vote if you consider it a bug.

Meta: 2010-07-19, Pepa

Tags: PowerShell bug