Home > Software design >  Recursive search for string within files on a drive
Recursive search for string within files on a drive

Time:11-23

I am trying to do a search for specific file within a directory with the following command:

gci -recurse -path "E:\" | select-string "searchContent" | select path

doing so gave me an insufficient memory error. I have seen other posts recommending piping it into foreach-object, but I couldn't figure out how to get it to work in my scenario. Any assistance appreciated!

CodePudding user response:

Just assign it to a variable, and then have a foreach loop that assigns each one to another variable.

$files = gci -recurse -path "E:\"

foreach ($fileName in $files)
{
 if ($fileName.Name -like "*searchContent*")
 {
      write-host $fileName.Name
 }
}

CodePudding user response:

I feel this should consume less memory. Can't tell for sure but you can let me know. The concept is the same but using [System.IO.StreamReader].

Note: This will keep on looking for all files it can find, if you need the loop to stop at first finding then a new condition should be added.

foreach($file in Get-ChildItem -Recurse -path "E:\" -File)
{
    $reader = [System.IO.StreamReader]::new($file.FullName)
    while(-not $reader.EndOfStream)
    {
        if($reader.ReadLine() -match 'searchContent')
        {
            $file.FullName
            break
        }
    }
    $reader.Dispose()
}
  • Related