Searching for Strings in Files with PowerShell

Image Description

Daily PowerShell #16

Scripting Daily PowerShell

November 1, 2021

The Select-String cmdlet is useful for finding strings and patterns in files.

In this post, we’ll look at the various ways to use Select-String to find strings in files.

Finding a String

To find a string within a set of files, you can use the basic Select-String parameter set. Specify the search string as the pattern and provide a wild card path.

This example searches for the class within the current directory and all files.

PS > Select-String -Pattern "class" -Path .\*

Program.cs:12:    public class Program
Startup.cs:24:    public class Startup

Finding a Pattern

You can also specify RegEx string to locate a pattern within files.

The following example finds strings that contain the number 0 through 9 in the current directory.

PS > Select-String -Pattern "[0-9]" -Path .\*

appsettings.Development.json:12:  "MagicLinkUrl": "https://localhost:5001"
appsettings.json:11:      "FileSizeLimit": 50024,
appsettings.json:12:      "RetainedFileCountLimit": 5
appsettings.json:14:  "Auth0": {

Get Matching File Information

When using Select-String, the default behavior returns a MatchInfo object that contains the matching line, the line number and the file name.

PS > Select-String -Pattern "[0-9]" -Path .\* | Select-Object -First 1 | Format-List *

IgnoreCase : True
LineNumber : 12
Line       :   "MagicLinkUrl": "https://localhost:5001"
Filename   : appsettings.Development.json
Path       : C:\src\ironmansoftware\appsettings.Development.json
Pattern    : [0-9]
Context    :
Matches    : {0}

Getting the Raw String

You can also use the -Raw parameter to just return the string itself.

PS > Select-String -Pattern "[0-9]" -Path .\* -Raw

"MagicLinkUrl": "https://localhost:5001"

Recursively Search Folders

You can use Select-String cmdlet in conjunction with Get-ChildItem to recursively search directories for files.

PS > Get-ChildItem * -Recurse | Select-String -Pattern "class" | Select-Object -First 1

.eslintrc:31:    "no-class-assign": 1,