Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why sls aka select-string does not work

Tags:

powershell

I am newbie on powershell. Today I tried something very simple

Alias  | sls -Pattern 'echo'

which produced echo, but what I want is Alias echo -> Write-Out.

In bash, you can just do

alias | grep 'echo'

My question is why sls does not work. BTW, if I replace sls with findstr, it worked.

like image 615
CS Pei Avatar asked Sep 01 '13 12:09

CS Pei


2 Answers

If you want to get an alias with a particular name you can do:

alias -name echo

The echo -> Write-Out is the DisplayName:

(alias -name echo).DisplayName

The Get-Alias command returns a sequence of objects, each of which represents a single command alias. When displayed in powershell, these objects are formatted as a table containing the CommandType, Name and ModuleName properties.

When you pipe into findstr, it is the string representations of these columns which are being filtered, so any match displays the whole table row:

Alias           echo -> Write-Output

When you pipe into Select-String each object is being bound to the -InputObject parameter of the Select-String cmdlet. Since Select-String operates on text, it just calls ToString on the received object to get its string representation.

ToString only returns the Name property. You can see this by executing the following:

alias | %{$_.tostring()}

Therefore any matches from Select-String only match on the alias name.

like image 155
Lee Avatar answered Nov 15 '22 03:11

Lee


select-string only behaves like grep when used with a text file. With a powershell object, the behavior changes (as Lee explained in his answer).

This can be demonstrated with:

alias > out.txt; cat out.txt | sls -pattern 'echo'

Which returns Alias echo -> Write-Output because now slsis operating on a text file.

The other solutions to do what you want are:

  1. alias | where DisplayName -like '*echo*'

  2. alias | out-string -stream | sls -pattern 'echo'

    This converts the powershell object to a string so that sls works like grep.

like image 27
wisbucky Avatar answered Nov 15 '22 04:11

wisbucky