Searching Files Using Index Search

by May 29, 2019

Windows Indexing indexes most files in your user profile and drives the fast file search in File Explorer. PowerShell can access the same mechanism. Here is a function that returns files based on content:

function Search-FileContent ([String][Parameter(Mandatory)]$FilterText, $Path = $home ) 
{ 
    $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 Contains('""$FilterText""') AND SCOPE='$Path'", $objConnection) 
    While (!$objRecordset.EOF ) 
    { 
        $objRecordset.Fields.Item("System.ItemPathDisplay").Value 
        $null = $objRecordset.MoveNext() 
    }     
}

To use it, specify a keyword. The code returns all files that contain the keyword:

 
PS> Search-FileContent -FilterText testcase -Path C:\Users\tobwe\Documents\
C:\Users\tobwe\Documents\Development\experiment1.zip
 

As you will quickly discover, Index Search does not return PowerShell scripts (*.ps1 files). By default, PowerShell scripts are not indexed. Go to the Index Service settings and include PowerShell scripts if you want to be able to search these files by content as well. Check here to learn more: https://devblogs.microsoft.com/scripting/use-windows-search-to-find-your-powershell-scripts/


psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!