1

other question doesn't answer this question, that comes up blank.

I have an array of 8 items I need to search through more than 100 files. So basically like a loop within a loop but with Powershell (newbie sorry).

I'm in the directory of the 100 files. I have built so far:

Get-ChildItem -path . -name | Get-Content | Select-String -Pattern $data

which as far as I understand: gets the list of files, piped to Get-Content to read all the file data, piped to select the pattern of the array items.

Lots of data out ofcourse, Get-Content needs to not be filtered to search it, but I only need to know which $data item was a match, and in which file it was found.

I think it hits true but then gives the the full content of the search I can't tell.

Don't know if we can do this all one liner or if it needs to be a script.

Any help or pointers to same much appreciated

sf2k
  • 592
  • 2
  • 6
  • 25

1 Answers1

0

The proposed duplicate post answers part of your question, but not the following aspect (emphasis added):

I only need to know which $data item was a match, and in which file it was found.

Get-ChildItem -File -LiteralPath . | 
  Select-String -List -Pattern $data |
  Select-Object Pattern, Path
  • As in the accepted answer to the linked duplicate, you can pipe Get-ChildItem output directly to Select-String for an efficient way to search the content of each input file.

    • Note: Select-String itself accepts file paths, via its -Path and -LiteralPath parameters; thus, Select-String -Path * -List -Pattern $data would work too (any directories among the matches are quietly ignored).

    • However, using output from a Get-ChildItem as input gives you more control over which files to search through, notably the ability to search recursively in a directory subtree (-Recurse).

  • -List limits searching each file's content to (at most) one match.

  • In the Microsoft.PowerShell.Commands.MatchInfo instances that Select-String outputs, the .Path property reflects the full path of the input file at hand, and .Pattern reflects which of the patterns passed to -Pattern matched.

    • As for the logic of which of the patterns is considered the match reported in .Pattern in case multiple patterns match on a single line:
      • It is the one that comes first in the -Pattern argument, irrespective of which potential matches comes first in a given input line - see this answer for details.
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • thanks so very much, key learning piece here was Select-Object then getting the pieces I wanted with Pattern and Path. I'll still have to manually verify but a prelim finding can be at least made – sf2k Jun 05 '23 at 15:54
  • Glad to hear it, @sf2k; my pleasure. Hope you can work out the rest. – mklement0 Jun 05 '23 at 16:26