filter outputs using select-string pipes

8,896

Solution 1

By default Out-String produce single string object, which contain all the output, so the following filter will select or discard all output as whole. You need to use -Stream parameter of Out-String cmdlet to produce separate string object for each output line.

Solution 2

Same answer, as a function and alias one can include in one's powershell profile:

function Find-Env-Variable (
           [Parameter(Mandatory = $true, Position=0)]
           [String]$Pattern){
    get-childitem ENV: | Out-String -Stream | select-string -Pattern "$Pattern"
}
Set-Alias findenv Find-Env-Variable
Share:
8,896

Related videos on Youtube

JL Peyret
Author by

JL Peyret

Interests/skills: PeopleSoft, SQL (Oracle, SQL Server, Postgresql), python, django.

Updated on September 18, 2022

Comments

  • JL Peyret
    JL Peyret over 1 year

    In bash, if I do the following, I will get all the environment variables with wd in them.

    env | grep "wd"
    

    Now, in Powershell, I know I could do

    get-childitem env:wd*
    

    But I want to pipe to select-string as a more generic approach, in order to filter what's coming in from its pipe, no matter what is to the left of the pipe. Just like grep.

    This doesn't filter anything, I get all environment variables.

    get-childitem env: | out-string | select-string -Pattern wd
    

    And this gets me nothing:

    get-childitem env: | select-string -Pattern "wd"
    

    I know I could use the following, and it is actually a better match if I filter only on the environment variable's name. But what if I want a quick and dirty filter a la grep? And especially, without knowing about the attributes of what's coming in from the pipe.

    get-childitem env: | where-object {$_.Name -like "wd*"}
    

    i.e. is there a Powershelll equivalent to grep usable in a pipe context, not just in the context of file searches, which select-string seems to cover well.