How to use 'Select-String' to filter lines from an output

9.8k views Asked by At

(first of all, I have searched SO,internet,youtube, for half an hour and didn't came with proper answer so I ask here)

I'm coming from the realm of routers and helpesk when you can simply filter string\s from an output with

"| include" (cisco) or "| findstr" (windows) like this:

findstr

I found out, on powershell we use 'Select-String' with the 'Pattern' switch.

For instance, i want to print out all the lines which contain the word 'Suffix' but it doesn't seem to work. What is the correct way, and can I use it without the need to creat a variable.

powershell

3

There are 3 answers

0
Theo On

Select-String is a cmdlet to find text in strings and files.
Get-NetIPAddress does not output a string, but an array of (CimInstance) objects.

To select only certain values from this array, you can pipe the result through to Select-Object like for instance

Get-NetIPAddress | Select-Object Suffix*

which outputs something like:

SuffixOrigin
------------
        Link
        Link
   WellKnown
        Link
        Dhcp
   WellKnown

This output on its own is probably not very usefull though..
You might want to end up with selecting a few more properties like with

Get-NetIPAddress -AddressFamily IPv4 | Select-Object IPAddress, InterfaceAlias, Suffix*
0
flaxel On

The cmdlet Get-NetIPAdress returns an array of objects which can be filter with the cmdlet Where-Object. But the disadvantage is that you must choose the field for the filtering. There is a short example in the documentation. Or you can use the cmdlet Select-Object:

Get-NetIPAddress | Select-Object *fix* 

Otherwise you can also use the command ipconfig to be able to filtering your output:

ipconfig | Select-String -Pattern "fix" 
2
Omer Meister On

Thank you both for clearing it out to me that the method retures objects in the form of array.

Unfortunately, I found working with 'Where-Object' and 'Select-Object' is complicated for this one time viewing purpose, so I converted the output to a string with the 'Out-String -Stream' cmdlet.

Get-NetIPAddress | Out-String -Stream | Select-String -Pattern "127.0.0.1"

It did the job well.