Windows PowerShell Select-String Cmdlet

Introduction to Windows PowerShell Select-String

Select-String not only opens a file, but also checks for a word, a phrase, or in fact any pattern match.  If you have used -pattern to make changes, PowerShell also tidies up and closes the file automatically.

Topics for PowerShell Select-String

 ♣

Introduction to: Select-String

The first objective is to set the -pattern parameter, which defines the string we are seeking.  Next comes the -path parameter, and as its name indicates, -path directs Select-String to the file’s location.

As you are reading this introduction, I expect you are thinking of possible applications for this Select-String construction.  Perhaps you wish to discover which documents contain a particular word?  Alternatively, you may be seeking a more complex search-And-replace operation.  My point is that while Select-String may be a bit-part in a bigger drama, you still need to master its syntax and switches.

Example 1 Select-String -path -pattern

The key to understanding Select-String is focussing on the two main switches -path and -pattern.  They say to me, ‘Where is the input?’ and, ‘What pattern do you want to match?’

To ensure that my examples work on your machine, you and I need to agree on the file location and the pattern to search.  To follow my examples successfully you need to embrace one of two tactics, either mimic my folder structure and patterns, or amend my script to fit in with your environment.

My folder happens to be called : D: \powershell\stuff.  These days I operate with the ISE version of PowerShell v 3.0.  Previously I navigated in PowerShell to the folder where I stored the files with the cmdlet examples that I am testing.  Then I just issue the .\filename command (.Dot slash followed by the name of cmdlet which stores the PowerShell instructions).

Here are three simple scripts which all produce the same result, but each employs a slightly different method.  By studying all three you will gain both perspective and ideas for the best method to use in your scripts.

Assumptions:
You have a file called gopher.txt. 
In gopher.txt is the word Guido.

Example 1a Select-String

Instructions

  1. Let us create the appropriate file in the appropriate folder, for example gopher.txt in D:\powershell\stuff.
  2. Put the word that you wish to search for in gopher.txt.  My word, is ‘Guido’, and you can see that in the script it comes directly after the -pattern parameter.
  3. Type this one line at the PowerShell command line:

Select-String -pattern "Guido" -path "D:\powershell\stuff\gopher.txt"

Note 1: Look closely at the dashes ‘-‘ PowerShell’s Verb-Noun (Select-String) pair are joined by a dash with no spaces.  The parameters -path and -pattern are introduced by a space dash then the parameter itself.

Example 1b Select-String Using the Variable $Location

This example is more complicated in that we are going to create a cmdlet, copy and paste the code below, then execute the cmdlet from inside PowerShell.

  1. Copy the cmdlet, then paste it into notepad, remember to save with a .ps1 extension,
    for example: selectstr.ps1. 
  2. Then I navigate in PowerShell to the folder where I saved the file, for example D: \powershell\stuff
  3. Issue the command .\selectstr
  4. If all else fails copy and paste the two lines into the PowerShell command line, then press ‘Enter’.

# PowerShell cmdlet to find the pattern Guido
$Location = "D:\powershell\stuff\gopher.txt"
Select-String -pattern "Guido" -path $Location

Expected outcome:
D:\powershell\stuff\gopher.txt:3:Guido is king

:3:  Means line number 3
:Guido is king  Refers to the line where the Pattern "Guido" occurs.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Example 1c Select-String (Wildcards *.*)

It is often useful to search a batch of files.  The simplest method is to use the famous * or *.* wildcard.

Instructions are the same as for example 1a

# PowerShell cmdlet to find the pattern Guido.  Note wildcard *
Select-String -pattern "Guido"  -path "D:\powershell\stuff\*.*"

Example 1d Select-String (Guy’s indulgence)

My main idea in Example 1c is to introduce an If… Else clause to cater for instances where the -pattern cannot be found.  To prepare for the ‘If’ logic I have introduced another variable called $SearchStr.  The second time you run this script you may wish to find and amend the "zzz" to a value that will ensure success.  If you accept my challenge then you can compare the outcome of the ‘If’ clause with the outcome of the ‘Else’ clause.

Instructions are the same as for example 1a

# PowerShell cmdlet to find the pattern zzz.
$Location = "D:\powershell\stuff\gopher.txt"
$SearchStr = "zzz"
$Sel = Select-String  -pattern $SearchStr -path $Location
If ($Sel -eq $null)
{
    write-host "$Location does not contain $SearchStr"
}
Else
{
    write-host "Found `n$Sel"
}

Write-host "end"

Note 2:  Let us study the ‘If’ test: If ($Sel -eq $null)  What this says if the value returned by Select-String is nothing ($Null).  Incidentally, there are two lls in $null.  Also, the correct syntax is -eq and not plain old =.

Note 3: The purpose of `n is to force a carriage return.

Note 4: Once the script runs successfully, amend $SearchStr ="zzz" to a string that exists in your document.

Engineer's Toolset v10Guy Recommends: SolarWinds Engineer’s Toolset v10

This Engineer’s Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset now!

Download your fully functional trial copy of the Engineer’s Toolset v10

Footnote – More parameters:

In addition to -pattern and -path, Select-String has more parameters; -Include and -exclude which are useful for fine tuning the files to be searched.  There is also the -caseSensitive switch to control uppercase and lowercase in the -pattern.  Select-String, like most PowerShell commands, is not case sensitive by default, hence the -caseSensitive parameter.

See more about PowerShell Parameters

Traps with Select-String

The biggest trap with all PowerShell’s file handling commands is ‘overthink’ By that I mean wasting time looking for open-file or save-file commands, which simply don’t exist.  What happens is that PowerShell opens, closes and saves files automatically.

A Real-life Example of Select-String

My practical problem was that I wanted to search for instances a particular string in a directory with hundreds of file.  If a file had duplicate entries, then I needed to know.

The PowerShell problem is how to create a stream of the files, then compare each file with my string value.  In the output I needed to know the filename.

To solve the problem, I employed four main commands, which you can see in the following script:

  1. Get-ChildItem – recurse
  2. foreach (loop) {what to do block}
  3. if (test) {output block}
  4. Select-String -pattern to match my string value.

# A real-life example of PowerShell’s Select-String
$i=0
$File = Get-ChildItem "H:\sports" -Include *.htm -recurse
$StringVid = "themesguy/google"
foreach ($Entry in $File) {
   $List = Select-String -pattern $StringVid $Entry
      if ($List.LongLength -gt 1) {
      "{0,-8} {1,-4} {2,18}" -f
      "Files ", $List.LongLength, $Entry.FullName;
      $i++
      }
}

Learning Point

Note 5:  If you want to get the above script to work, focus on the $File and $StringVid variables.  Specifically change their values to match your file location and search pattern.

Note 6: To find out more about the -f formatting switch consult SN4 in the Syntax section.

 See more examples of Select-String on this page »

Guy Recommends: SolarWinds Free Network Bandwidth MonitorFree Real-Time Bandwidth Monitor

This freeware monitor is great for checking whether your network’s load-balancing is performing as expected, for example, are two interfaces are getting about equal traffic?

It’s easy to install and straightforward to configure. You will soon be running tests to see how much network bandwidth your applications consume.

The GUI has a lovely balance between immediate network traffic data in the middle, combined with buttons to seek related data and configuration settings. Give this monitor a try, it’s free! 

Download your free network bandwidth monitor

If you need more comprehensive network analysis software:
Download a free trial of NPM (Network Performance Monitor)

Example of Select-String Kindly Sent by trebboR

# A real-life example of PowerShell’s Select-String
# Makes a test.txt file with testcontent
"0123456789abcdefghijklmnopqrstuvwxyz`
ABCDEFGHIJKLMNOPQRSTUVWXYZZYXWVUTSRQPONMLKJIHGFEDCBA`
zyxwvutsrqponmlkjihgfedcba9876543210" >> "C:\test3.txt"
# read file into $a
$a = Get-Content "C:\test3.txt"
#$a
# Check what you want
$a.Contains("zz") #False
$a.Contains("ZZ") #True
$a.IndexOf("ZZ") # 61
#-=[trebboR.EU]=-

Further Research on PowerShell’s Select-String

Clear-Host
help Select-String -full

I found these the most useful Select-String parameters -Include, -Context and -NotMatch.  I have found -Exclude disappointing, particularly in PowerShell v 1.0.

Select-String -Context

# PowerShell Select-String -Context
$FilePath = ""D:\powershell\stuff\*.*
Select-String -pattern "Guido"  -path $FilePath -context 3

Note 7: This returns 3 lines either side of the pattern Guido, just so that you can see which of multiple results you is most interesting.  One use of this technique is troubleshooting eventlogs.  I also recommend splatting to format your parameters.

Sister Cmdlet – Out-String

The only other cmdlet with the noun ‘string’ is: Out-String.

Note 8: In PowerShell Select-String has an alias called: sls.

 See more examples of Select-String in action »

Summary of PowerShell’s Select-String Cmdlet

Select-String is a useful instruction for opening files, and then searching their contents for the phrase specified by the -pattern parameter.  My advice is to get into the rhythm of the command: for example: Verb-Noun then -parameter.  For example: Select-String -path -pattern. As expected, you can use wildcards in the path.

Once you have mastered the basic construction look real life tasks where you can employ this technique to find words or phrases that are hiding somewhere within your files.

If you like this page then please share it with your friends

 


See more PowerShell examples for syntax constructions

PowerShell Tutorials   • Syntax   • Pipeline   • Quotes   • Remove-Item   • ItemProperty

Select-String  • -replace string   • Group-Object   • Sort-Object   • PowerShell Splatting

Windows PowerShell cmdlets   • Windows PowerShell  • New-Item  • PowerShell New Object

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.