PowerShell包括获取文件名

时间:2018-03-24 15:43:13

标签: powershell

我有以下代码从文件夹中的多个文件中提取字符串(字符串)并将字符串保存在文本文件中。我想在output.txt文件中添加文件名作为每行的开头,那么如何获取我正在分析的每个文件的文件名?

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

1 个答案:

答案 0 :(得分:2)

在单个ForEach-Object区块中浏览匹配项:

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