Home > Back-end >  Powershell - list found and not found strings during search
Powershell - list found and not found strings during search

Time:06-24

I have a script that will search for strings or a list of strings and create a report. What I'm having trouble with is, I now need to know what strings were NOT found as well as those that were. Would anyone be able to offer an alteration to the script below to achieve this?

Thanks, -Ron

$searchWords=Get-Content "C:\Directory containing file\Text_To_Search_For.txt"

# List the starting(parrent) Directory here - the script will search thropugh every file and every sub-directory - starting fromn the one listed below  
Get-Childitem -Path "C:\Start my search here\" -Recurse | 
  Select-String -Pattern $searchWords | 

# the output will contain the [Found] word, the document it found it in and the line contents/line number containing the found string 
    Select Filename,Line,@{n='SearchWord';e={$_.Pattern}}, LineNumber

CodePudding user response:

As per my comment above:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-string?view=powershell-7.2

Get-Help -Name Select-String -Examples

A quick example from the guidance in the help files. You of course can tweak as you need to.

Clear-Host
Get-ChildItem -Path 'D:\Temp' | 
ForEach-Object {
    IF  (Select-String -Path $PSItem.FullName -Pattern 'test')
    {"Target word found in filename "   $PSItem.FullName}
    Else {'Word not found'}
}


# Results
<#
...
Word not found
Word not found
Word not found
Target word found in filename D:\Temp\UserData.csv
Word not found
Target word found in filename D:\Temp\UsersList.csv
Target word found in filename D:\Temp\Using Inner classes in C#.txt
Target word found in filename D:\Temp\VerboseLogFile.log
Word not found
Word not found
Word not found
...
#>

This can be tweaked to get the lines in the file where the pattern is found vs just the filename as well.

CodePudding user response:

Use the common -OutVariable (-ov) parameter to capture all matches output by Select-String, which allows you to analyze all matches after the fact, via Compare-Object:

# Note the `-OutVariable allMatches` part, which records Select-String's
# output objects in self-chosen variable $allMatches.
Get-ChildItem -Path "C:\Start my search here" -Recurse | 
  Select-String -OutVariable allMatches -Pattern $searchWords | 
  Select-Object Filename,Line,@{n='SearchWord';e={$_.Pattern}}, LineNumber

# Get the array of distinct words (patterns) that matched.
$wordsWithMatches = $allMatches.Pattern | Select-Object -Unique

# Now output those that *didn't* match.
Compare-Object $searchWords $wordsWithMatches -PassThru
  • Related