我是一位非常新手的Powershell学生,他的任务是让以下代码正常工作,并且我在标记的行中不断收到空管道错误,并给出空管道错误'。经过几个小时的研究,我仍然难以理解是什么导致了这一点。该脚本应该搜索Application.evtx日志并返回过去24小时内的任何错误。我非常感谢能帮助我指明正确方向的任何帮助。 这是代码:
#look for Errors script
#Creates Function named CheckLogs
Function CheckLogs()
{
# Defines a named parameter $logfile as a string
param ([string]$logfile)
if(!$logfile) {write-host "Usage: ""C:\Windows\System32\winevt\Logs\Application.evtx"""; exit}
# Accesses the file stored in $logfile variable and looks for the string "ERROR"
cat $logfile | Select-string "ERROR" -SimpleMatch |select -expand line |
foreach
{
$_ -match '(.+)\s\[(ERROR)\]\S(.+)'| Out-Null
new-object psobject -Property@{Timestamp=[datetime]$matches[1];Error=$matches[2]}
| #Gives Empty Pipeline Error
where {$_.timestamp -gt (get-date).AddDays(-1)}
$error_time=[datetime]($matches[1])
if ($error_time -gt (Get-Date).AddDays(-1))
{
write-output "CRITICAL: There is an error in the log file $logfile around
$($error_time.ToShortTimeString( ))"; exit(2)
}
}
write-output "OK: There were no errors in the past 24 hours."
}
CheckLogs "C:\Windows\System32\winevt\Logs\Application.evtx" #Function Call
答案 0 :(得分:1)
您不能将管道|
字符单独放在一行上。您可以使用|
结束一行,然后在下一行继续管道。
这应该有效:
new-object psobject -Property@{Timestamp=[datetime]$matches[1];Error=$matches[2]} |
where {$_.timestamp -gt (get-date).AddDays(-1)}