Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Created July 13, 2022 19:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save indented-automation/d9d20dfb09d24ddee7c5654f86fe32f6 to your computer and use it in GitHub Desktop.
Save indented-automation/d9d20dfb09d24ddee7c5654f86fe32f6 to your computer and use it in GitHub Desktop.
Event log subscriber
function Watch-WinEvent {
<#
.SYNOPSIS
Watch for events matching a query in the event log.
.DESCRIPTION
Watch for events matching a query in the event log.
#>
[CmdletBinding()]
param (
# The computer name to get events from.
[Parameter(Position = 0)]
[string]$ComputerName,
# A credential to use for this operation.
[PSCredential]$Credential,
# The name of the event log.
[string]$LogName
# An event log QueryList written in XML.
[string]$Query,
# Wait for the node if it reboots then resume watching.
[switch]$Wait
)
$activity = 'Watching for events on {0}' -f $ComputerName
do {
try {
Write-Progress -Activity $activity -Status Connecting
$sessionParams = @{
ComputerName = $ComputerName
SessionOption = New-PSSessionOption -IdleTimeout 60000 -OperationTimeout 0
ErrorAction = 'Stop'
}
if ($PSBoundParameters.ContainsKey('Credential')) {
$sessionParams['Credential'] = $Credential
}
$session = New-PSSession @sessionParams
$count = 1
Write-Progress -Activity $activity -Status Watching
$invokeParams = @{
Session = $session
ScriptBlock = {
$eventLogQuery = [System.Diagnostics.Eventing.Reader.EventLogQuery]::new(
$using:LogName,
'LogName',
$using:Query
)
$eventLogWatcher = [System.Diagnostics.Eventing.Reader.EventLogWatcher]::new(
$eventLogQuery
)
$params = @{
InputObject = $eventLogWatcher
EventName = 'EventRecordWritten'
}
Register-ObjectEvent @params
$eventLogWatcher.Enabled = $true
while ($true) {
Wait-Event | Get-Event | ForEach-Object {
$eventRecord = $_.SourceEventArgs.EventRecord
$eventRecord.PSObject.Properties.Add(
[System.Management.Automation.PSNoteProperty]::new(
'Message',
$eventRecord.FormatDescription()
)
)
$eventRecord
$_ | Remove-Event
}
}
}
}
Invoke-Command @invokeParams
} catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
Write-Progress -Activity $activity -Status ('Waiting for connection {0}' -f ($count++))
Start-Sleep -Seconds 5
} catch {
Write-Error -ErrorRecord $_
}
} while ($Wait)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment