【发布时间】:2013-02-22 02:53:27
【问题描述】:
如何使用 powershell 跟踪特定的 Windows 事件日志? 有可能吗?
【问题讨论】:
-
尾巴?作为离子监测仪?或者获取特定事件的尾部?
标签: windows powershell event-log tail
如何使用 powershell 跟踪特定的 Windows 事件日志? 有可能吗?
【问题讨论】:
标签: windows powershell event-log tail
我有时会这样做:
$idx = (get-eventlog -LogName System -Newest 1).Index
while ($true)
{
start-sleep -Seconds 1
$idx2 = (Get-EventLog -LogName System -newest 1).index
get-eventlog -logname system -newest ($idx2 - $idx) | sort index
$idx = $idx2
}
【讨论】:
根据 MSDN 文档:
Get-WinEvent旨在替换Get-EventLogcmdlet 运行 Windows Vista 和更高版本 Windows 的计算机。Get-EventLog仅在经典事件日志中获取事件。Get-EventLog是 保留在 Windows PowerShell 中以实现向后兼容性。
在我自己需要跟踪非-经典事件日志(这可能是新事件日志吗?)的刺激下,这是非常简洁的代码@mjolinor 改用 Get-WinEvent:
Set-PSDebug -Strict
function Get-WinEventTail($LogName, $ShowExisting=10) {
if ($ShowExisting -gt 0) {
$data = Get-WinEvent -provider $LogName -max $ShowExisting
$data | sort RecordId
$idx = $data[0].RecordId
}
else {
$idx = (Get-WinEvent -provider $LogName -max 1).RecordId
}
while ($true)
{
start-sleep -Seconds 1
$idx2 = (Get-WinEvent -provider $LogName -max 1).RecordId
if ($idx2 -gt $idx) {
Get-WinEvent -provider $LogName -max ($idx2 - $idx) | sort RecordId
}
$idx = $idx2
# Any key to terminate; does NOT work in PowerShell ISE!
if ($Host.UI.RawUI.KeyAvailable) { return; }
}
}
为方便起见,我添加了一些花里胡哨:
ShowExisting 参数将其调整为任意数字。Get-WinEvent 的默认值相反)对记录进行排序。【讨论】:
首先,谢谢迈克尔!
对我的用例进行了微调,包括显示整个多行消息值。
function Get-WinEventTail($Provider="JobRequestQueueConsumerBackgroundService", $ShowExisting=10) {
$formatProperty = @{ expression={$_.TimeCreated}; label="TimeCreated"},
@{ expression={$_.Message}; label="Message"; width=100}
if ($ShowExisting -gt 0) {
$data = Get-WinEvent -ProviderName $Provider -max $ShowExisting
if ($data) {
$data | sort RecordId | Format-Table -Property $formatProperty -Wrap
$idx = $data[0].RecordId
}
}
else {
$idx = (Get-WinEvent -ProviderName $Provider -max 1).RecordId
}
while ($true)
{
start-sleep -Seconds 1
$idx2 = (Get-WinEvent -ProviderName $Provider -max 1).RecordId
if ($idx2 -gt $idx) {
Get-WinEvent -ProviderName $Provider -max ($idx2 - $idx) | sort RecordId | Format-Table -Property $formatProperty -Wrap
}
$idx = $idx2
# Any key to terminate; does NOT work in PowerShell ISE!
if ($Host.UI.RawUI.KeyAvailable) { return; }
}
}
Get-WinEventTail
-Wrap 选项是显示多行消息所必需的,否则省略号会截断第一行末尾的消息。设置列宽没有帮助。
【讨论】: