我有一个日志文件,我正在尝试解析,但一直无法找到解决方案。我已经复制了下面的日志文件的一部分。每组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++
}
}
答案 0 :(得分: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[]
,其中包含您所需匹配的行号和行值。
答案 1 :(得分: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
中,它已经被换行符分割,因此您不必这样做。