一种方法是这样做
$result = Get-ChildItem "\\$server\$Path" -Filter "*.log" -File |
Select-String -Pattern $text -SimpleMatch |
Select-Object -ExpandProperty Line |
ForEach-Object {
if ($_ -match '([a-z]{3,}\s*\d{2}\s*\d{2}:\d{2}:\d{2}\.\d{3}\s*\d{4}).*GUID ([\d.]+)') {
'{0},{1}' -f $matches[1], $matches[2]
}
}
$result | Out-File $logfile -Append
解释:
- 我在
Select-String cmdlet 中添加了开关-SimpleMatch,因为您似乎想完全匹配$text,而且它在那里不使用正则表达式,这将是最佳选择。
-
Select-Object -ExpandProperty Line 可以返回一个匹配行的数组,所以我通过管道将它传递给 ForEach-Object 以循环
-
if (..) 使用正则表达式 -match,如果该条件为 $true,我们将执行大括号内的任何操作。
此外,此测试(如果为 $true)会自动设置一个 $matches 对象数组,我们使用这些匹配项输出一个逗号分隔的行,然后将其收集到变量 $result 中。
- 最后我们简单地将 $result 输出到一个文件中
正则表达式详细信息:
( Match the regular expression below and capture its match into backreference number 1
[a-z] Match a single character in the range between “a” and “z”
{3,} Between 3 and unlimited times, as many times as possible, giving back as needed (greedy)
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\d Match a single digit 0..9
{2} Exactly 2 times
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\d Match a single digit 0..9
{2} Exactly 2 times
: Match the character “:” literally
\d Match a single digit 0..9
{2} Exactly 2 times
: Match the character “:” literally
\d Match a single digit 0..9
{2} Exactly 2 times
\. Match the character “.” literally
\d Match a single digit 0..9
{3} Exactly 3 times
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\d Match a single digit 0..9
{4} Exactly 4 times
)
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
GUID\ Match the characters “GUID ” literally
( Match the regular expression below and capture its match into backreference number 2
[\d.] Match a single character present in the list below
A single digit 0..9
The character “.”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)