Search in files with PowerShell and return files, line numbers.
The script in this article will allow you to enter a search directory and the value you’re looking for. As the script finds files that contain your search, the file name, line number, and line content will be displayed.
After this script was created, I later found that select-string was returning parts of words, instead of only the full word: returning “Description” when the search value was “script.” To correct this, this regex bit was used in the pattern: -Pattern "\b($String_Search)\b", surrounding the variable with “\b(” and “)\b” …. \b being the beginning and end of the word and parentheses specifying a group of characters (or word, in this case).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# # Search a directory for a string and return the file name, line number, and line. ############################################### ########### Prompt for values ################# write-host -NoNewline -ForegroundColor green -BackgroundColor black "Enter the folder to search in" $Folder_Search = Read-Host ' ' write-host -NoNewline -ForegroundColor green -BackgroundColor black "Enter the value to search for" $String_Search = Read-Host ' ' write-host `n ########### Get files of interest ############# $Files = Get-ChildItem -Path $Folder_Search | where {($_.Extension -eq ".csv" -OR $_.Extension -eq ".txt" -OR $_.Extension -eq ".html") -and $_.PSIsContainer -eq $False} ########### Loop through files ################ Foreach ($item in $Files){ ########### Check file name value ############# IF($item.FullName -like "*$String_Search*"){ write-host -nonewline -ForegroundColor white -BackgroundColor darkgray "Found in file name" write-host -NoNewline `t '|' `t write-host -ForegroundColor Yellow $item.FullName write-host `n } ########### Search within file for values ###### $Search_Content = (Select-String -Pattern "\b($String_Search)\b" -Path $item.Fullname) ######## If value is found, write the details ## IF($Search_Content){ IF(($Search_Content.Line).Length -gt 255){ $Line = ($Search_Content.Line).Substring(0,255) }ELSE{ $Line = ($Search_Content.Line) } write-host -nonewline -ForegroundColor white -BackgroundColor darkgray "Found search value within file" write-host -NoNewline `t '|' `t write-host -ForegroundColor Green $item.FullName write-host Line Number: $Search_Content.lineNumber `t Line: $line write-host `n } } |