Powershell script for search substring into text files or folder

Sometimes you need find substring or group of strings into text files in folder. For resolve this task I use Powershell script. It displays the number of occurrences of the string and file names where the substring is found.


$subStrings = @("Substing1",
"Substing2",
"Substing3"); # your substrings

$Path = "C:\"; # folder with files
$result = "";

foreach ($element in $subStrings) {
$i=0;
$fileName = "";
# This code snippet gets all the files in $Path that end in ".txt".
Get-ChildItem $Path -Filter "*.txt" -Recurse |
Where-Object { $_.Attributes -ne "Directory"} |
ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern $element) {
$i++;
$fileName  += $_.FullName + "rn";
}
}
$result += "Quantity of " + $element + " = " + $i + "rn";
$result += $fileName  + "rn";
}

$result > "C:\result.txt" #output file with search result

You can to search into files with any extension. Change line number 12 -Filter parameter («*.txt»).

If you want to search into only one folder (without recursion) then remove “-Recurse” to the original Get-ChildItem command.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.