6

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.

  • Out-String -Stream – user364455 Nov 25 '16 at 21:42
  • get-childitem env: | Out-String -Stream | select-string -Pattern wd was just the ticket. Thx! I dunno if you care, but I'll definitely accept it if you post it as an answer. – JL Peyret Nov 25 '16 at 21:53
6

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.