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.
- $path = read-host "Enter the path for the log files "
- $Searchstring = read-host "Enter the string to be searched "
- $Logs = Get-ChildItem -path $path -recurse -include *.log
- foreach($Log in $Logs)
- {
- $StringExist = Select-String -Path $log.fullname -pattern $Searchstring
- if($StringExist)
- {
- write-host "String found in " $Log.name -fore green
- $log.name | out-file $scriptbase\FileContainingString.txt -append
- }
- else
- {
- write-host "String not found in " $Log.name -fore cyan
- }
- }
Complete Code
- $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
- $LogFile = ".\SearchStringPatch-$LogTime.rtf"
-
- # Add SharePoint PowerShell Snapin
-
-
- if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
- Add-PSSnapin Microsoft.SharePoint.Powershell
- }
-
- $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
- Set-Location $scriptBase
-
- #Deleting any .rtf files in the scriptbase location
- $FindRTFFile = Get-ChildItem $scriptBase\*.* -include *.rtf
- if($FindRTFFile)
- {
- foreach($file in $FindRTFFile)
- {
- remove-item $file
- }
- }
-
- $TestPath = test-path -path $scriptbase\FileContainingString.txt
- if($testpath)
- {
- remove-item $scriptbase\FileContainingString.txt
- }
-
- start-transcript $logfile
-
- $path = read-host "Enter the path for the log files "
- $Searchstring = read-host "Enter the string to be searched "
- $Logs = Get-ChildItem -path $path -recurse -include *.log
- foreach($Log in $Logs)
- {
- $StringExist = Select-String -Path $log.fullname -pattern $Searchstring
- if($StringExist)
- {
- write-host "String found in " $Log.name -fore green
- $log.name | out-file $scriptbase\FileContainingString.txt -append
- }
- else
- {
- write-host "String not found in " $Log.name -fore cyan
- }
- }
- stop-transcript
Execution procedure
- Step 1: Download the script
- Step 2: Navigate to the script path
- Step 3: Execute the script
Conclusion
Thus this article outlines how to search for a specific string pattern in thousands of log files using a PowerShell script.