我有一个长日志文件,如下所示:
2016-06-09 09:44:33 0 Appname C:\folder\file.ext 2016-06-09 09:45:33 0 Appname C:\folder\file.ext 2016-06-09 09:46:33 3010 Appname C:\folder\file.ext 2016-06-09 09:56:33 0 Appname C:\folder\file.ext 2016-06-09 09:57:33 0 Appname C:\folder\file.ext
正如您所看到的,在每行的第21个字符处,都有一个代码显示应用程序是否正确安装。 (0,3010或其他数字)
我只想制作它,以便所有代码都显示在弹出窗口中,以便于查看是否存在任何错误。
我知道如何制作弹出部分,如下例所示:
$codes = "test text"
$wshell = New-Object -ComObject WScript.Shell
$wshell.Popup("$codes", 0, "Test", 0)
现在,有没有办法“选择”文件中每行所需的字符,让我们说字符21到24所以我可以获得如下输出:
0 0 3010 0 0弹出窗口中的
?
答案 0 :(得分:1)
将日志作为CSV导入为空格分隔文件。然后,选择第3列。
示例:
# Extract the codes from the file into an array
$codes = Import-Csv -path .\name.log -Header "date","time","code","type","file" -Delimiter " " |
Select-Object -ExpandProperty code
# Make sure each code is displayed on a newline
$formattedCode = $codes -join [Environment]::NewLine
# Display the codes in a popup
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup($formattedCode,0,"Test",0)
我根据您提供的文件内容示例使用此代码对此进行了测试。
$content = @"
2016-06-09 09:44:33 0 Appname C:\folder\file.ext
2016-06-09 09:45:33 0 Appname C:\folder\file.ext
2016-06-09 09:46:33 3010 Appname C:\folder\file.ext
2016-06-09 09:56:33 0 Appname C:\folder\file.ext
2016-06-09 09:57:33 0 Appname C:\folder\file.ext
"@
$codes = $content |
ConvertFrom-Csv -Header "date","time","code","type","file" -Delimiter " " |
Select-Object -ExpandProperty code
$formattedCode = $codes -join [Environment]::NewLine
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup($formattedCode,0,"Test",0)
答案 1 :(得分:1)
短代码:
a == b
如果你想只选择不同的0:
$wshell = New-Object -ComObject WScript.Shell
$wshell.Popup((import-csv "c:\temp\log.txt" -Header DateLog, TimeLOg, Code -Delimiter ' ').Code -join "`n", 0, "Test", 0)
答案 2 :(得分:0)
您可以在空格处分割线条,如下所示:
Get-Content 'C:\path\to\your.log' | ForEach-Object {
$date, $time, $code, $app, $file = $_ -split ' ', 5
New-Object -Type PSObject -Property @{
Timestamp = [datetime]"$date $time"
Code = [int]$code
Application = $app
File = Get-Item $file
}
}
或使用正则表达式解析行,如下所示:
$re = '(?<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (?<code>\d+) ' +
'(?<app>\w+) (?<file>.*)'
Select-String 'C:\path\to\your.log' -Pattern $re |
Select-Object -Expand Matches |
ForEach-Object {
New-Object -Type PSObject -Property @{
Timestamp = [datetime]$_.Groups['timestamp'].Value
Code = [int]$_.Groups['code'].Value
Application = $_.Groups['app'].Value
File = Get-Item $_.Groups['file'].Value
}
}
当然,从解析的值中创建对象是可选的,但如果您需要进一步处理数据,它可能会派上用场。