我有一个包含几个月日志的文件,我想只将特定数据的日志存储到csv文件中。
示例日志数据:
22-06-21 09:06:09 15SS1B Equip = Z39 Text -0003254设备已在线添加
2022-07-21 09:06:09 15SS2B Equip = Z40 Text -0003254设备已在线添加
2022-08-21 09:06:09 15SS3B Equip = Z41 Text -0003254设备已在线添加
2022-09-21 09:06:09 15SS4B Equip = Z42 Text -0003254设备已在线添加
我得到以下列的结果:IgnoreCase, LineNumber, Line, Filename, Path, Pattern, Context, Matches。我只对Line列的结果感兴趣。
谢谢你的帮助。谢谢。
这是我的代码:
$data = Get-Content 'log.log' | Select-String -Pattern "2022-08-21" | Export-CSV -Path 'output.csv' -NoTypeInformation
我的请求是获取内容并将它们导出到新表中,如:
Date Time Number Type
2022-06-21 09:06:09 15SS1B Equip
我将在此使用正则表达式,以便解析出所需的部分并将其作为对象的属性输出:
$dateToSearch = '2022-08-21'
$regex = "^(?<date>$dateToSearch)s+(?<time>d{2}:d{2}:d{2})s+(?<number>[a-zd]+)s+(?<type>w+)s+=.*"
Get-Content -Path 'log.log' | Where-Object { $_ -match $regex } |
Select-Object @{Name = 'Date'; Expression = {$matches['date']}},
@{Name = 'Time'; Expression = {$matches['time']}},
@{Name = 'Number'; Expression = {$matches['number']}},
@{Name = 'Type'; Expression = {$matches['type']}} |
Export-CSV -Path 'output.csv' -NoTypeInformation
或者使用循环来代替计算属性:
$dateToSearch = '2022-08-21'
$regex = "^(?<date>$dateToSearch)s+(?<time>d{2}:d{2}:d{2})s+(?<number>[a-zd]+)s+(?<type>w+)s+=.*"
Get-Content -Path 'log.log' | Where-Object { $_ -match $regex } | ForEach-Object {
[PsCustomObject]@{
Date = $matches['date']
Time = $matches['time']
Number = $matches['number']
Type = $matches['type']
}
} | Export-CSV -Path 'output.csv' -NoTypeInformation
结果
Date Time Number Type
---- ---- ------ ----
2022-08-21 09:06:09 15SS3B Equip
您是否正在寻找这样的东西,我为一行做了这个,同样可以用于多行
$line = "2022-06-21 09:06:09 15SS1B Equip = Z39 Text -0003254 Equipment has been added on-line"
$data = $line.Split("=")[0]
$result = $data.Split(" ") # A Space in between quotes
[pscustomObject]@{
Date = $result[0]
Time = $result[1]
Number = $result[2]
Type = $result[3]
}