Custom Windows File and Pattern Search in PowerShell script
4 minute read
December 26, 2016
Custom Windows Search
I recently worked on a project where I was tasked to create a custom search for a client and he wanted a specific search that would
look at 1 text file filled with windows path locations and 1 text file that has specific words to search for.
Here is the script:
Breakdown of script
The first function I found on an answer this question on superuser.com
This is used for formatting the size of files found in the script.
Format-FileSize function takes one integer that is the Length property of a file and formats it according to its size. i.e. 1KB, 1MB…
Header of the script menu
This is the opening screen for the script which shows the Powershell Version from the start and then I do a Read-Host to show this header for the script.
Browse for folder Dialog box
The next part I found some code that will open the BrowseForFolder dialog windows that allows you to navigate to the folder
where the locations and patterns text files are located. Then it checks if both files exists if not then it exits the script.
Get-ChildItem with Select-Object
The function is used when creating a new object for Select-Object and the name of it is Size. The expression is going to be the function Format-FileSize and
we will pass it the Length property which is the number of bytes for the file.
The major part of the script
I perform 2 foreach loops starting with the locations text file and start with the first location then I start the next foreach
thru all the patterns to search for in the first location and all its subfolders using this line:
To search all recursively down the folders we must get all the files using Get-ChildItem and using Where-Object.
I filter all the files out by using $_.PSIsContainer -eq $false. * If we wanted folders then this would be equal to True instead of false
The other condition is where Name property is -like “$pattern”. * I use the star(*) character as a wildcard on both sides so we can find the pattern anywhere in the title.
I then pipe the results to Select-Object to get all custom properties:
Folder - Directory of file
Size - Use Format-FileSize function and pass Length of file in bytes.
Last Modified Date - LastWriteTime of file.
Owner - Use Get-Acl cmdlet and pass it the fullName of the file