Powershell - Tail Windows Event Log? Is it possible?

前端 未结 3 644
你的背包
你的背包 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:28

    First, thank you Michael!

    Slight refinement for my use case that includes showing the entire multi-line message value.

        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
    

    The -Wrap option was necessary to show a multi-line message, otherwise ellipsis would truncate the message at the end of the first line. Setting the column width did NOT help.

提交回复
热议问题