如何只读取.log文件的最后两行?以下脚本读取返回错误状态的完整.log文件。对于我的特殊情况,返回每个.log文件的正确状态的字符串写在最后两行。
function Get-Status($file) {
if (Select-String -Quiet 'Finished with errors' $_.FullName) {
return "ERROR"
} elseif (Select-String -Quiet 'Finished with warnings' $_.FullName) {
return "WARNING"
} elseif (Select-String -Quiet 'Finished.' $_.FullName) {
return "SUCCESS"
} else {
return "FAILED"
}
}
Get-ChildItem C:\logfolder\*.log | % {
[PSCustomObject] @{
Name = $_.Name;
Date = $_.LastWriteTime;
Status = Get-Status($_.FullName)]
}
}
发布于 2021-01-08 18:31:46
您可以使用Get-Content
和仅选择最后两行来读取文件内容,如下所示:
$fileContent = Get-Content -Path $file -Tail 2
因此,将此代码添加到您的Get-Status
函数应该会返回正确的状态:
function Get-Status($file) {
$fileContent = Get-Content -Path $file -Tail 2
if (Select-String -Quiet -Pattern 'Finished with errors' -InputObject $fileContent) {
return "ERROR"
} elseif (Select-String -Quiet -Pattern 'Finished with warnings' -InputObject $fileContent) {
return "WARNING"
} elseif (Select-String -Quiet -Pattern 'Finished.' -InputObject $fileContent) {
return "SUCCESS"
} else {
return "FAILED"
}
}
发布于 2021-01-08 18:32:03
在最新版本的PowerShell Get-Content中支持-Tail参数,因此您可以将Get-Content转换为select字符串,例如,对于第一个if语句:
Get-Content -Tail 2 $_.FullName | Select-String -Quiet 'Finished.'
发布于 2021-01-08 18:36:49
另一种变体是在Get-Status
函数中使用switch
:
function Get-Status([string]$file) {
# get the last two lines of the log and recombine them with a newline
switch -Regex ((Get-Content -Path $file -Tail 2) -join "`r`n") {
'(?m)^Finished with error' { 'ERROR' ; break}
'(?m)^Finished with warning' { 'WARNING' ; break}
'(?m)^Finished' { 'SUCCESS' ; break}
default { 'FAILED'}
}
}
Get-ChildItem -Path 'C:\logfolder' -Filter '*.log' -File | ForEach-Object {
[PSCustomObject] @{
Name = $_.Name
Date = $_.LastWriteTime
Status = Get-Status $_.FullName
}
}
请注意,对于PowerShell,您应该在函数名和参数之间使用空格字符,而不是将此参数放在括号中。
https://stackoverflow.com/questions/65627015
复制相似问题