我试图通过 Powershell 中的Get-EventLog
获取 Windows Sever 2008 机器的意外关机时间。我可以通过搜索 6008 的EventID
事件并选择message
来接近,但我需要在字段中解析以获取它发生的时间(而不是事件触发的时间)。
我试图使用replacementstrings[x]
,但我找不到如何指定要使用的字段(messages
),无法获得结果。
get-eventlog-LogName System-ComputerName svr-name | Where-Object {$_.EventID-eq 6008-AND $_.timegenerated-gt (get-date).adddays(-30)}| select message
产生这个:
Message
-------
The previous system shutdown at 3:35:32 AM on 7/29/2014 was unexpected.
The previous system shutdown at 3:40:06 PM on 7/10/2014 was unexpected.`

从远程主机检索所有事件并在本地计算机上对其进行过滤通常效果不佳,因为这样您就可以通过网络传输大量不相关的事件,只是为了将其丢弃。Get-EventLog
具有按事件 ID 或源上给定时间戳之前 / 之后过滤消息的选项,因此最好使用这些选项来预先选择您实际感兴趣的消息。
$log = 'System'
$server = 'svr-name'
$id = [uint64]"0x80000000" + 6008
$date = (Get-Date).AddDays(-30)
$fmt = 'h:mm:ss tt on M\/d\/yyyy'
$culture = [Globalization.CultureInfo]::InvariantCulture
Get-EventLog -LogName $log -ComputerName $server -InstanceId $id -After $date | ? {
$_.Message -match 'at (\d+:\d+:\d+ [ap]m on \d+/\d+/\d+) was unexpected'
} | select MachineName, TimeGenerated,
@{n='Crashtime';e={[DateTime]::PExact($matches[1], $fmt, $culture)}}
管道生成一个对象列表,其属性为MachineName
,TimeGenerated
和Crashtime
(最后一个是calculated property)。如果您在变量(例如$evt
)中收集管道的输出,则可以访问第三个对象的Crashtime
属性,如下所示:
$evt = .\script.ps1
$evt[2].Crashtime

使用正则表达式,你可以把它拉出来。
$Messages = (get-eventlog -LogName System -ComputerName svr-name | Where-Object {$_.EventID -eq 6008 -AND $_.timegenerated -gt (get-date).adddays(-30) }| select message)
$Messages | ForEach-Object {
$Matched = $_.Message -match "([0-9]{1,2}:.*[0-9]{4})"
if ($Matched) {
Write-Output "System rebooted at $($Matches[1])"
}
}
可能有更好的方法,但我不知道是什么:)
我的系统输出示例
System rebooted at 4:34:30 PM on 4/20/2014
System rebooted at 1:48:38 PM on 1/21/2014
System rebooted at 1:37:12 PM on 1/21/2014
System rebooted at 1:22:01 PM on 1/21/2014
System rebooted at 4:41:21 PM on 11/22/2013
更容易
get-eventlog system | where-object {$_.EventID -eq "6008"} | fl
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(52条)