-2

I have a problem. I'm going to search files on my computer for keywords in the files. The keyword is for example "C:\Project". I get error when running this script below. But when i'm deleting C:\ in the search string it's working. But i'm interested in to search with C:\ in the beginning. Can someone help me with correction in the script?

$path = 'D:\Cross'
$searchword = 'C:\Project'
$Filename = '*.config'

Get-ChildItem $path -Include "$Filename" -Recurse | ForEach-Object { 
  If (Get-Content $_.FullName | Select-String -Pattern $searchword ){
    $PathArray += $_.FullName
  }
}

Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Either add switch `-SimpleMatch` to the `Select-String` cmdlet or escape the backslash in the searchstring with another backslash. – Theo Oct 19 '21 at 11:11

1 Answers1

1

Select-String defaults to regular expressions, so if you want a simple substring search instead, use the -SimpleMatch switch:

Get-Content $_.FullName | Select-String -Pattern $searchword -SimpleMatch

or make sure you escape any regex metacharacters:

Get-Content $_.FullName | Select-String -Pattern $([regex]::Escape($searchword))

You can also simplify your code significantly by using Where-Object and piping the file objects directly to Select-String instead of manually invoking Get-Content:

$filesWithKeyword = Get-ChildItem $path -Include "$Filename" -Recurse |Where-Object { $_ |Select-String -Pattern $searchword -SimpleMatch |Select-Object -First 1 }

$filesWithKeyword now contains all the FileInfo objects for which Select-String found at least 1 occurrence of the keyword in the corresponding file on disk. Select-Object -First 1 ensure the pipeline aborts as soon as the first occurrence is found, preempting the need to read large files all the way to the end.

The whole script thus becomes:

$path = 'D:\Cross'
$searchword = 'C:\Project'
$Filename = '*.config'

$filesWithKeyword = Get-ChildItem $path -Include "$Filename" -Recurse |Where-Object { $_ |Select-String -Pattern $searchword -SimpleMatch |Select-Object -First 1 }

Write-Host "Contents of ArrayPath:"
$filesWithKeyword.FullName
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206