我尝试解析日志文件并输出格式化结果 结果文件已创建,但在运行脚本后为空。
源日志文件:
2011-07-08 14:34:40.609 Ber 8 [R: 1] Http -> GET http://test.com:80/api/test?__crd=78F5WE6WE
2011-08-08 12:34:51.202 Inf 9 [R: 1] Http <~ GET http://TEST.com:80/api/gs?__crid=7B9790431B8 [304 Not Modified] [11.774 ms]
2011-08-08 15:38:52.166 War 8 [R: 33] [Excn][Type:Api][Err:300][HTTPStatus:NotFound][Message:PCNDLS_. ISE Account : 111][CorrId:hvukyhv78r5564]
Write-Host 'Hello! My Name is test !'
$Files = Get-ChildItem C:\log\1\* -Include *.log
New-Item -ItemType file -Path C:\log\result.txt –Force
foreach ($File in $Files)
{
$StringMatch = $null
$StringMatch = select-string $File -pattern "[Exception]|[304 Not Modified]"
if ($StringMatch) {out-file -filepath C:\log\result.txt -inputobject $StringMatch }
$regex = 'Line\s+(\d+):\s+([^;]+);([^;]+);([^;]+);(.+)'
[regex]::Matches($StringMatch, $regex) | ForEach-Object {
[PsCustomObject]@{
ID = $_.Groups[1].Value
Time = $_.Groups[2].Value
Status = $_.Groups[3].Value
URL = $_.Groups[4].Value
Message = $_.Groups[5].Value
}
}
}
答案 0 :(得分:1)
我认为您的搜索模式存在问题,但通常您似乎正在与自然的Powershell做事方式作斗争。如果您使用管道方法,您将使您的生活更轻松。请尝试以下示例:
$regex = 'Line\s+(\d+):\s+([^;]+);([^;]+);([^;]+);(.+)'
$pat = "\[Exception\]|\[304 Not Modified\]"
$path = "C:\log\1\*.log"
$file = "C:\log\result.txt"
Remove-Item $file -ErrorAction SilentlyContinue
Get-ChildItem $path | Select-String -Pattern $pat | Select -ExpandProperty line | % {
$_ | Add-Content $file
# Add code to create object here
}
或者你不需要你可以做的对象:
Get-ChildItem $path | Select-String -Pattern $pat | Select -ExpandProperty line | Add-Content $file