This shows you how you can search in files for a specific content with Windows Powershell. This “replaces” the Windows command-line utility “findstr”. In the Unix/Linux world you mostly use the command grep for doing the same.
grep syntax
grep (options) files.txt
grep example
grep "text I search" *.log
In Windows Powershell we can use the Select-String to search strings in files
Select-String -Path C:\temp\*.log -Pattern "Contoso"
If you need some more options, for example you need also check subfolders (-Recurse) or you need additional filter for files you wanna check, you can use the Get-Childitem first.
Get-ChildItem C:\temp -Filter *.log -Recurse | Select-String "Contoso"
If you have to copy all the files with a specific content, you can simply add a Copy-Item cmdlet.
Get-ChildItem C:\temp -Filter *.log -Recurse | Select-String "Contoso" | Copy-Item -Destination C:\temp2
More Information about Select-String:
PS C:\> Get-Help Select-String
NAME
Select-String
SYNOPSIS
Finds text in strings and files.
SYNTAX
Select-String [-Path] <string[]> [-Pattern] <string[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>] [-Encoding <string>] [-Exclude <string[]>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonParameters>]
Select-String -InputObject <psobject> [-Pattern] <string[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>] [-Encoding <string>] [-Exclude <string[]>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonParameters>]
DESCRIPTION
The Select-String cmdlet searches for text and text patterns in input strings and files. You can use it like Grep in UNIX and Findstr in Windows.
Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.
However, you can direct it to detect multiple matches per line, display text before and after the match, or display only a Boolean value (true or false) that indicates whether a match is found.
Select-String uses regular expression matching, but it can also perform a simple match that searches the input for the text that you specify.
Select-String can display all of the text matches or stop after the first match in each input file. It can also display all text that does not match the specified pattern.
You can also specify that Select-String should expect a particular character encoding, such as when you are searching files of Unicode text.
RELATED LINKS
Online version: http://go.microsoft.com/fwlink/?LinkID=113388
about_Comparison_Operators
about_Regular_ExpressionsREMARKS
To see the examples, type: “get-help Select-String -examples”.
For more information, type: “get-help Select-String -detailed”.
For technical information, type: “get-help Select-String -full”.PS C:\>