1

我有一个正在尝试解析的日志文件,但找不到解决方案。我在下面复制了一部分日志文件。每组 3 行是一个错误。

csrak17 remove int_rpsmkt
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
csrak17 add int_rpsops
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
csrak17 remove int_rpssales
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
csrak17 remove int_tpd
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
csrak17 remove int_trpit
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)

我正在将日志文件加载到数组中,并且返回带有错误代码的行没有问题。我需要做的是首先找到一条带有“错误:HPDMG1064E”的行,然后检查该行后两行,看它是否包含“添加”一词(如第二组示例)。

有没有办法根据在另一个数组中找到的值返回数组中的一行?当然,我将遍历文件并重复该过程。

这是我到目前为止所拥有的,但由于某种原因它只返回一行到我的输出文件。此外,如您所见,我没有任何代码可以尝试根据当前索引查找另一个索引。

$logs = Get-Content C:\Temp\test\ProdtamResults_HPDMG1064E_errors.doc
$Value = "HPDMG1064E"

foreach($log in $logs) {
    $i = 0
    while ($i -le $logs.length-1) {

        if ($logs[$i] -match $Value)
            {
                return $logs[$i] | out-file C:\Temp\test\results.txt
            }
    $i++
    }
}
4

2 回答 2

3

试试这个

$logs = Get-Content C:\Temp\test\ProdtamResults_HPDMG1064E_errors.doc
$Value = "HPDMG1064E"

gc $logs | select-string -Pattern $value -Context 3 | 
? { $_.context.precontext[1] -match '\sadd\s' } | select linenumber, line

这将返回psobject[] 带有行号和所需匹配的行值的 a。

于 2013-09-18T14:31:01.047 回答
1

这是一个简化的测试用例,当第 (i-2) 行包含“add”时,它将输出第 i 行:

$file = @"
csrak17 remove int_rpsmkt
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
csrak17 add int_rpsops
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
csrak17 remove int_rpssales
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
csrak17 remove int_tpd
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
csrak17 remove int_trpit
Could not perform the administration request
Error: HPDMG1064E   The group member was not found. (status 0x14c01428)
"@;

$lines = $file -split "`n"

$Value = "HPDMG1064E";
for($i=0; $i -lt $lines.Count; $i++) {
  if($lines[$i] -match "HPDMG1064E") {
    if($lines[$i-2] -match "add") {
      Write-Host $lines[$i]; #or do something else
    }
  }
}

在您的代码Get-Content中,它已经被换行符分割,所以您不必这样做。

于 2013-09-18T14:30:16.023 回答