Select-String can be an alternative to Linux’s amazing and well known grep tool. However, grep must be downloaded and setup on the Windows system which might not be possible or convient to do so. A great built-in alternative on Windows PowerShell is Select-String which can do regular expression searching similar to grep.

Goal is to have Select-String to only return the match text or the found reuslt.

Quick Summary

  • Select-String returns Matches and within it has Value which has the exact text match of the regex without any extra text:
    • (cat .\results.txt | Select-String '<a.*?>.*?</a>').Matches.Value

Example: curl a webpage, search a pattern

Let’s say we curl’d a webpage and we want to extract the <a>...</a> tags.

Let’s first save the results to a text file results.txt for easier testing:

curl https://www.example.com > results.txt

Let’s read the text file with cat alias for Get-Content and pipe into Select-String with pattern <a.*?>.*?</a>. The pattern itself is not important in this case, as we’re just using it as an example.

(Get-Content results.txt | Select-String '<a.*?>.*?</a>')

The output will show the found regex pattern along with all the text around it. If thte line’s were simpler it might be usable, but in complex files it likely isn’t.

Snippet from the output (notice result was found but additional text was given):

... <p><a href="https://www.iana.org/domains/example">More information...</a></p> ...

So something like $results = (Get-Content results.txt | Select-String '<a.*?>.*?</a>'), would output a blob of text.

However, we can access the .Matches variable to see all the matches, in this case one was found:

Groups    : {0}
Success   : True
Name      : 0
Captures  : {0}
Index     : 7
Length    : 70
Value     : <a href="https://www.iana.org/domains/example">More information...</a>
ValueSpan :

.Matches is an array so it can have multiple matches. .Matches has access to Groups, Success, Name, Captures, Index, Length, Value, ValueSpan. The most interesting here is our exact match in Value.

Now we can use .Matches.Value to see the exact matches:

$results = (cat .\results.txt | Select-String '<a.*?>.*?</a>').Matches.Value

Write-Host $results

We can access each result individually by $results[i] or all the results by $results.

Output all results, in this case one result:

<a href="https://www.iana.org/domains/example">More information...</a>

🆒🆒🆒🆒

Until next time ✌️