如果你需要从一个文件夹中的多个文件中解析这个,你可以使用
$files = Get-ChildItem -Path 'Path\To\The\Files' -File
foreach ($file in $files) {
Get-Content -Path $file.FullName |
Select-String -Pattern '\[.*,([^,]+,[^\]]+)\]' -AllMatches |
ForEach-Object { $_.Matches.Groups[1].Value }
}
正则表达式详细信息
\[ Match the character “[” literally
. Match any single character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
, Match the character “,” literally
( Match the regex below and capture its match into backreference number 1
[^,] Match any character that is NOT a “,”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
, Match the character “,” literally
[^\]] Match any character that is NOT a “]”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
\] Match the character “]” literally
结果可能类似于
BBPRINTER01.domain.local,AG-printer-S4
BBPRINTER02.otherdomain.local,AG-printer-S5
BBPRINTER03.somedomain.local,AG-printer-S6
编辑
根据您的评论,要输出文件路径和正则表达式匹配,最简洁的方法是输出 objects 而不是字符串,并将这些结果捕获到变量中。使用对象,您还有机会写入可以在 Excel 中打开的结构化 CSV 文件:
$files = Get-ChildItem -Path 'Path\To\The\Files' -File
$result = foreach ($file in $files) {
Get-Content -Path $file.FullName |
Select-String -Pattern '\[.*,([^,]+,[^\]]+)\]' -AllMatches |
ForEach-Object {
[PsCustomObject]@{
'SourceFile' = $file.FullName
'Regex-Output' = $_.Matches.Groups[1].Value
}
}
}
# output on screen
$result | Format-Table -AutoSize
# write to CSV file
$result | Export-Csv -Path 'Path\To\The\result.csv' -UseCulture -NoTypeInformation