Select-String not only opens a file, but also checks for a word, a phrase, or in fact, any pattern match.
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.
The key to understanding select-String is studying 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, you and I need to agree on the file location and the pattern to search. To be successful 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. My working technique is to navigate in powershell to the folder where I store 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.
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.
Guy Recommends: SolarWinds Engineer's Toolset v10
The Engineer's Toolset v10 provides a
comprehensive console of utilities for troubleshooting computer problems. Guy says
it helps me monitor what's occurring on the network, and the tools
teaches me more about how the system literally operates.
There are so many good gadgets, it's like having free rein of a
sweetshop. Thankfully the utilities are displayed logically: monitoring, discovery, diagnostic, and Cisco tools.
Download your copy of the Engineer's Toolset v 10
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.
Copy the cmdlet, then paste it into notepad, remember to save with a .ps1 extension, for example: selectstr.ps1.
Then I navigate in PowerShell to the folder where I saved the file, for example D: \powershell\stuff
Issue the command .\selectstr
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.
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 1: 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 2: The purpose of `n is to force a carriage return.
Note 3: Once the script runs successfully, amend $SearchStr ="zzz" to a string that exists in your document.
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.
The biggest trap with all PowerShell's file handling commands is looking for open-file or save-file commands. They simply don't exist. What happens is that PowerShell opens, closes and saves
files automatically.
My practical problem was that I wanted to search for instances a particular string. If a file had duplicates, 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:
get-ChildItem - recurse
foreach (loop) {what to do block}
if (test) {output block}
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 1: 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 2: To find out more about the -f formatting switch consult SN4 in the Syntax section.
Guy Recommends: SolarWinds LANSurveyor
LANSurveyor will produce a neat diagram of your network topology. But that's
just the start;
LANSurveyor can
create an inventory of the hardware and software
of your machines and network devices. Other neat features include dynamic
update for when you add new devices to your network. I also love the ability to export
the diagrams
to Microsoft Visio.
Finally, Guy bets that if you take a free trial of LANSurveyor then you will
find a device on your network that you had forgotten about, or someone else
installed without you realizing!
# 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]=-
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.
Please write in if you see errors of any kind. Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.
Guy
Recommends: Orion's NPM - Network Performance Monitor
Orion's performance monitor is designed for detecting network outages.
A network-centric
view make it easy to see what's working, and what needs your attention.
This utility guides you through troubleshooting by indicating whether the
root cause is faulty equipment or resource overload.