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.
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.
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 sls
is operating on a text file.
The other solutions to do what you want are:
alias | where DisplayName -like '*echo*'
alias | out-string -stream | sls -pattern 'echo'
This converts the powershell object to a string so that sls
works like grep
.
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