Powershell script to search content in files

This is a small PowerShell function which allows you to search within the content of all files inside a specific directory or its sub-directories. Very useful in some situations…

#Usage: script.ps1 <keyword> <search path> <extension>
#Example: script.ps1 JeffWouters D:\Company\Projects .docx

function WordSearch ($keyword, $folder, $extension)
{
$objConnection = New-Object -com ADODB.Connection
$objRecordSet = New-Object -com ADODB.Recordset
$objConnection.Open(“Provider=Search.CollatorDSO;Extended Properties=’Application=Windows’;”)
$objRecordSet.Open(“SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE System.FileExtension = ‘$extension’ AND (Contains(Contents,’$keyword’)) AND System.ItemPathDisplay LIKE ‘$folder\%'”, $objConnection)
if ($objRecordSet.EOF -eq $false) {$objRecordSet.MoveFirst() }

while ($objRecordset.EOF -ne $true) {
$objRecordset.Fields.Item(“System.ItemPathDisplay”).Value
$objRecordset.MoveNext()
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *