【问题标题】:PowerShell (Eventlogs: How to compare dates/time?)PowerShell(事件日志:如何比较日期/时间?)
【发布时间】:2014-07-15 10:04:11
【问题描述】:

到目前为止,我从未使用过 PowerShell,但现在我不得不使用。 (别担心,我知道如何用其他语言编程。)

我必须做的:

有 2 个事件日志: “EventID 等于 3317,Event Level 等于 Error”和“EventID 等于 3317,Event Level 等于 Information”

如果有一个级别为“错误”的事件之后没有级别为“信息”的事件,则输出必须为“关键”。 如果在此事件之后有一个级别为“信息”的事件,级别为“错误”,则输出必须为“正常”。 (如果没有具有该 ID 的事件,则一切正常。)

现在的问题是我不知道如何比较从这些行中获得的两个日期值...

get-eventlog -log application -EntryType error  –newest 1 | where {$_.eventID -eq 3317}
get-eventlog -log application -EntryType information  –newest 1 | where {$_.eventID -eq 3317}

其他解决方案也值得赞赏。 ;)

您好, 塞德里克

编辑(代码):

#Error:
$e_error = (get-eventlog -log application -EntryType error | where {$_.eventID -eq 3317} | Select -First 1).TimeGenerated
write-host "Error:       $e_error"

#Information:
$e_info = (get-eventlog -log application -EntryType information | where {$_.eventID -eq 3317} | Select -First 1).TimeGenerated
write-host "Information: $e_info"

if (($e_error) -and ($e_info)) {  #If $e_error (Error) & $e_info (Information) are not empty (events exists)
  $timediff = (new-timespan –start $e_error -end $e_info).TotalSeconds  #Difference
  if ($timediff -gt 0) {  #If $e_info (Information) newer than $e_error (Error)
    $res = "Ok"
  } else {  #If one of them or both are empty
    $res = "Critical"
  }
} else {
  if (($e_error) -and (!($e_info))) {  #If $e_error (Error) exists but not $e_info (Information)
    $res = "Critical"
  } else {  #If non of both or only Information exists
    $res = "Ok"
  }
}

write-host $res

【问题讨论】:

    标签: powershell event-log


    【解决方案1】:

    TimeWritten 或 TimeGenerated 值将为您提供比较日期和时间...

    get-eventlog -log application -EntryType error  –newest 1 | where {$_.eventID -eq 3317} | Select TimeGenerated, TimeWritten
    

    你也可以这样做来拉出那个属性

    (get-eventlog -log application -EntryType error  –newest 1 | where {$_.eventID -eq 3317}).TimeGenerated
    

    我提出的另一个建议是在选择最后一个错误之前过滤事件。否则,如果快速连续发生另一个错误,您可能会错过一个条目。所以你的查询基础应该是这样的:

    get-eventlog -log application -EntryType error  | where {$_.eventID -eq 3317} |  | Select -First 1
    

    【讨论】:

    • 谢谢!,我会投票,但我没有足够的声誉。 ;)
    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多