Powershell - Tail Windows Event Log? Is it possible?

前端 未结 3 642
你的背包
你的背包 2021-02-05 11:56

How can i use powershell to tail a specific windows event log? Is it possible?

3条回答
  •  时光说笑
    2021-02-05 12:44

    Per MSDN docs:

    Get-WinEvent is designed to replace the Get-EventLog cmdlet on computers running Windows Vista and later versions of Windows. Get-EventLog gets events only in classic event logs. Get-EventLog is retained in Windows PowerShell for backward compatibility.

    And spurred on by my own need to tail a non-classic event log (would that be an event log nouveau perchance?) here is the wonderfully concise code of @mjolinor repurposed to use 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; }
        }
    }
    

    I added in a few bells and whistles for convenience:

    • By default it shows the last 10 lines of the log initially, then concatenates new entries as they occur--you can adjust that to any number via the ShowExisting parameter.
    • It sorts records with oldest first (contrary to Get-WinEvent's default) due to the natural order that tail requires.
    • You can press any key to terminate (but not in PowerShellISE).

提交回复
热议问题