WMI Eventing (Subscription): Unterschied zwischen den Versionen

Aus Wiki-WebPerfect
Wechseln zu: Navigation, Suche
Zeile 57: Zeile 57:
 
     Name = 'ServiceConsumer'
 
     Name = 'ServiceConsumer'
 
     Text = 'A change has occurred on the service: %TargetInstance.DisplayName%'
 
     Text = 'A change has occurred on the service: %TargetInstance.DisplayName%'
     FileName = "C:\Scripts\Log.log"
+
     FileName = "C:\Temp\Log.log"
 
}
 
}
 
$consumerResult = Set-WmiInstance @wmiParams
 
$consumerResult = Set-WmiInstance @wmiParams

Version vom 24. September 2021, 07:13 Uhr

Example: Windows Eventlogs (All Windows Eventlogs)

Register/Create Subscription (remote)

##Event log watch -- Windows Eventlog
$WMI = @{
    SourceIdentifier = "RHEEventlog"
    Query = "select * from __InstanceCreationEvent where TargetInstance isa 'Win32_NtLogEvent'" #and (TargetInstance.EventCode = '3108')"
    Action = {
        $Eventrhe = $event.SourceEventArgs.NewEvent.TargetInstance
        $InsertStrings = $Eventrhe.InsertionStrings #InsertStrings = Windows Eventlog Variables
        $MemberNames = (($Eventrhe | Get-Member) | ? {($_.MemberType -eq "Property") -and !($_.Name -match "__")}).Name
 
            Foreach ($MemberName in $MemberNames) {
                Write-Host $MemberName":" $Eventrhe.$MemberName
            } 
 
            $Nr = 0
            Foreach ($InsertString in $InsertStrings) {
                $Nr++
                Write-Host "InsertString($nr):" $InsertString -ForegroundColor red
            }
        Write-Host "---------------------------------------------------------------" -ForegroundColor Green
    }
}
$Null = Register-WMIEvent @WMI -ComputerName <Remote-Hostname>


Unregister/Remove Subscription

 Unregister-Event -SourceIdentifier "RHEEventlog"


Get Subscriptions

 Get-EventSubscriber


Example: Service Modification

The following Service modification subscription logs everytime a service changed (start, stop).

#Filter
#Creating a new event filter
$wmiParams.Class = '__EventFilter'
$wmiParams.Arguments = @{
    Name = 'ServiceFilter'
    EventNamespace = 'root\CIMV2'
    QueryLanguage = 'WQL'
    Query = "select * from __instanceModificationEvent within 5 where targetInstance isa 'win32_Service'"
}
$filterResult = Set-WmiInstance @wmiParams
 
 
#Consumer
$wmiParams.Class = 'LogFileEventConsumer'
$wmiParams.Arguments = @{
    Name = 'ServiceConsumer'
    Text = 'A change has occurred on the service: %TargetInstance.DisplayName%'
    FileName = "C:\Temp\Log.log"
}
$consumerResult = Set-WmiInstance @wmiParams
 
 
#Binding
$wmiParams.Class = '__FilterToConsumerBinding'
$wmiParams.Arguments = @{
    Filter = $filterResult
    Consumer = $consumerResult
}
$bindingResult = Set-WmiInstance @wmiParams