Thursday 27 May 2021

Searching for String within Multiple Files using Powershell

 I recently had a situation where I had to search for a particular string within a large number of files. More specifically, I was looking for what file contained a set of  text used for a menu on a website - the problem is I didn't know which file contained the text, but I knew what I was looking for. The web server had a large number of xml, html and css files, so I quickly put together a powershell script to search these files quickly and was able to find what I was looking for within a matter of minutes! Certainly faster than manually opening files and performing a CTRL + F find within them.

$files = get-childitem -path "C:\inetpub\wwwroot\*.css" -recurse
foreach ($file in $files)
    {
    $filecontent = get-content $($file.fullname)
    $lookup = $filecontent | select-string "What I'm Looking For"
    if ($lookup)
    {write-host "$($file.fullname)"}
    }

The first line searches the folder C:\inetpub\wwwroot for any file ending in .css.  The -recurse switch means it searches all subfolders within C:\inetpub\wwwroot as well. You can of course change the search directory and file type being searched for

$files = get-childitem -path "C:\inetpub\wwwroot\*.css" -recurse

The next section is a ForEach loop that goes through every file that is found within $files (as outlined above). The content of the file is read into the $filecontent variable

$filecontent = get-content $($file.fullname)

Next we perform a search of all the text within the $filecontent variable for a particular string of text. In this example the text we're looking for is "What I'm Looking For" - change this to whatever string of text you are trying to find tin these files. The result of the search is stored in the $lookup variable. If no match is found then $lookup will be null.

$lookup = $filecontent | select-string "What I'm Looking For"

Finally, if a result is found and the $lookup variable is not null, the full name of the file is written to the screen

if ($lookup)
    {write-host "$($file.fullname)"}

This little script saved me a heap of time - as built in windows search functions are pretty unreliable and don't search for content within files. Hope it is able to help you as well.

No comments:

Post a Comment