Introduction

This article provides a Powershell Script to search for a specific string in multiple log files using a PowerShell script.

Need for this script

Consider a scenario where you have thousands of .log files and you need to find whether a specific string pattern is available or not in each of the log files. PowerShell becomes handy otherwise you may end up searching the string for days.

The following piece of code gets input from the user on the log files location path and the string to be searched for and loops through all the log files under the given location and searches for the specific string. An output file (FileContainingString.txt) with the details of the log file that has the specific string is generated and placed under the same location where the script is placed.

  1. $path = read-host "Enter the path for the log files "
  2. $Searchstring = read-host "Enter the string to be searched "
  3. $Logs = Get-ChildItem -path $path -recurse -include *.log
  4. foreach($Log in $Logs)
  5. {
  6. $StringExist = Select-String -Path $log.fullname -pattern $Searchstring
  7. if($StringExist)
  8. {
  9. write-host "String found in " $Log.name -fore green
  10. $log.name | out-file $scriptbase\FileContainingString.txt -append
  11. }
  12. else
  13. {
  14. write-host "String not found in " $Log.name -fore cyan
  15. }
  16. }
Complete Code
  1. $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
  2. $LogFile = ".\SearchStringPatch-$LogTime.rtf"
  3. # Add SharePoint PowerShell Snapin
  4. if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
    {
  5. Add-PSSnapin Microsoft.SharePoint.Powershell
  6. }
  7. $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
  8. Set-Location $scriptBase
  9. #Deleting any .rtf files in the scriptbase location
  10. $FindRTFFile = Get-ChildItem $scriptBase\*.* -include *.rtf
  11. if($FindRTFFile)
  12. {
  13. foreach($file in $FindRTFFile)
  14. {
  15. remove-item $file
  16. }
  17. }
  18. $TestPath = test-path -path $scriptbase\FileContainingString.txt
  19. if($testpath)
  20. {
  21. remove-item $scriptbase\FileContainingString.txt
  22. }
  23. start-transcript $logfile
  24. $path = read-host "Enter the path for the log files "
  25. $Searchstring = read-host "Enter the string to be searched "
  26. $Logs = Get-ChildItem -path $path -recurse -include *.log
  27. foreach($Log in $Logs)
  28. {
  29. $StringExist = Select-String -Path $log.fullname -pattern $Searchstring
  30. if($StringExist)
  31. {
  32. write-host "String found in " $Log.name -fore green
  33. $log.name | out-file $scriptbase\FileContainingString.txt -append
  34. }
  35. else
  36. {
  37. write-host "String not found in " $Log.name -fore cyan
  38. }
  39. }
  40. stop-transcript
Execution procedure



Conclusion

Thus this article outlines how to search for a specific string pattern in thousands of log files using a PowerShell script.