10

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.

2
  • 1
    Out-String -Stream Commented Nov 25, 2016 at 21:42
  • 1
    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. Commented Nov 25, 2016 at 21:53

2 Answers 2

10

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.

4

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 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.