1
votes

I have the following code to extract a string (strings) from multiple files in a folder and save the strings in a text file. I'd like to add the filename as the beginning of each line in the output.txt file so how do I get the filename for each file that I'm analyzing?

$input_path = ‘path’
$output_file = ‘output.txt’
$regex = '(.+?)'
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
1

1 Answers

2
votes

Go through the matches in a single ForEach-Object block:

Select-String -Path $input_path -Pattern $regex -AllMatches | ForEach-Object {
  foreach($Match in $_.Matches){
    '{0}: {1}' -f $_.FileName,$Match.Value
  }
} > $output_file