- PowerShell allows you to handle different types of events: engine, .NET, WMI and more.
- Cmdlets such as Register-ObjectEvent and Get-Event allow you to work with events in real time.
- Tasks can be automated by detecting events such as process shutdowns, file changes, or system logs.
- PowerShell allows you to read, filter, and export events from the standard and custom logs. Windows.
Would you like to learn how to efficiently manage events in PowerShell and leverage its capabilities to automate tasks or detect system activity? Although PowerShell is known as a system administration tool, its true power comes when used in conjunction with events. In this article, we explain EVERYTHING you need to know about using events with PowerShell, based on official documentation and specialized technical articles.
From system logs to custom events, PowerShell lets you capture, analyze, and react to any type of event.We will see both the commands We'll cover both basic and advanced examples using .NET Framework classes. We'll also teach you how to view events, subscribe to them, and trigger automated actions based on the captured event. Let's get started.
Types of events you can handle in PowerShell
PowerShell has the ability to work with different types of events, each with its own characteristics. Here are the main ones:
- PowerShell Engine Events: such as OnIdle (when there is no activity) and Exiting (when the session is closed).
- .NET Framework Object Events: such as closing processes, modifying files, etc.
- WMI and CIM Events: Ideal for more advanced monitoring scenarios, available since PowerShell 3.0.
- Custom events: created with
New-Event
to handle specific contexts within your scripts.
View and work with logs with PowerShell
One of the most common ways to work with events in PowerShell is by querying the Windows event logs.. You can access them from the Graphical Event Viewer (run eventvwr
), but PowerShell gives you much finer control with cmdlets Get-EventLog
y Get-WinEvent
. Also, if you want to learn how to detect specific system problems, you can check out This event viewer diagnostic in Windows 11.
Basic queries with Get-EventLog
This cmdlet is useful for working with logs classics like Application, System o Security. Some examples:
- List all logs:
Get-EventLog -List
- Get the last 10 events:
Get-EventLog -LogName System -Newest 10
- Filter by type:
Get-EventLog -LogName System -EntryType Error
- Filter by message:
Get-EventLog -LogName System -Message *dominio*
More advanced queries with Get-WinEvent
For modern or custom logs, Get-WinEvent
It is more powerful. It accepts XML-based filters, allows you to work with specific IDs like 4104 (used for registered PowerShell scripts), and access records like Microsoft-Windows-PowerShell/Operational.evtx
. If you want to learn more about managing logs and events in Hyper-V, check out Manage logs and events in Hyper-V.
For example, to extract all fragments from a script executed (event 4104 with the same ScriptBlock ID):
$StoreArrayHere = Get-WinEvent -FilterHashtable @{ Path="C:\SampleEVTX\Microsoft-Windows-PowerShell%4Operational.evtx"; ProviderName="Microsoft-Windows-PowerShell"; Id = 4104 } | Where-Object { $_.Message -like '*51baf005*' }
You can sort the fragments and join them together to reconstruct the complete script.. A key practice in forensic analysis or tasks of ciberseguridad. For more details on how to detect malware through logs, query types of malware.
Creating and subscribing to custom events
PowerShell allows you to create custom events with New-Event
. This is useful for generating internal events within complex scripts. You can subscribe to them using Register-EngineEvent
.
Example:
Register-EngineEvent -SourceIdentifier MyEvent -Action { Write-Host "Se ha producido el evento personalizado" }
New-Event -SourceIdentifier MyEvent -MessageData "Algo pasó"
You can also view events in the active queue with Get-Event
and eliminate them with Remove-Event
For more advanced management, check out Override the firewall in Windows.
Subscribing to .NET Framework events
With Register-ObjectEvent
You can react to events from .NET objectsFor example, you can detect when an application is closed, a file is created, or a new log is entered into the system.
Example with the calculator process
$calc = ::Start("calc.exe")
Register-ObjectEvent -InputObject $calc -EventName Exited -Action {
Write-Host "La calculadora se cerró"
}
Example with FileSystemWatcher
$fsw = New-Object System.IO.FileSystemWatcher
$fsw.Path = "C:\Users\Public"
Register-ObjectEvent -InputObject $fsw -EventName Created -Action { Write-Host "Archivo nuevo detectado" }
Example with System.Diagnostics.EventLog
$log = New-Object System.Diagnostics.EventLog
$log.Log = "Security"
Register-ObjectEvent -InputObject $log -EventName EntryWritten -Action { Write-Host "Evento de seguridad escrito" }
In these cases, every time the monitored event occurs, the action block will be executed automatically..
PowerShell Engine Events
There are few, but useful for automating common tasks:
- PowerShell.OnIdle: It is activated when there is no activity.
- PowerShell.Exiting: It is launched when the console is closed.
For example, to save command history:
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -SupportEvent -Action {
Get-History | Export-Clixml "$home\ps_history.xml"
}
This script can be included in your PowerShell profile, and when you start a new session, you can retrieve the history with:
If (Test-Path "$home\ps_history.xml") {
Add-History -InputObject (Import-Clixml "$home\ps_history.xml")
}
Review and manage subscriptions
All active events and subscriptions in a session can be reviewed with: Get-EventSubscriber
To cancel them, just use Unregister-Event
.
For example:
Get-EventSubscriber | Unregister-Event
You can also use the parameter -Force
if any subscription is not seen directly.
Automation with background or remote events
PowerShell supports event forwarding from background or remote sessions. You achieve this by using the parameter -Forward
in the subscription cmdlets.
Example with a background job:
Start-Job -ScriptBlock {
Register-EngineEvent -SourceIdentifier JobEvent -Forward
New-Event -SourceIdentifier JobEvent -Message "Trabajo terminado"
}
Your main session can capture and act on that event..
Applications in cybersecurity and forensics
PowerShell 5.0 introduced script block logging (Event ID 4104), which stores the full contents of executed scripts. This is crucial for detecting suspicious activity.
If a script is long, it is saved as multiple fragments in the logs. You can reconstruct it by filtering by ScriptBlock ID and sorting the events. There is also the script ExtractAllScripts.ps1
which automates this task. Using it, it's possible to combine fragments that survive log rotation and recover much of the executed content.
Although PowerShell has been criticized in the past for its potential for malicious use, when properly configured it becomes an essential tool for defending against attacks, auditing changes, and automatically reacting to anomalous behavior. To understand how to detect suspicious activity, review Configure DHCP and DNS on Windows Server.
By mastering events in PowerShell, you can create more secure, efficient, and automated environments. From monitoring processes to handling network or file events, PowerShell's flexibility is enormous. The key is understanding how to subscribe to relevant events and how to use that information to take action, thus strengthening your responsiveness and security.
Passionate writer about the world of bytes and technology in general. I love sharing my knowledge through writing, and that's what I'll do on this blog, show you all the most interesting things about gadgets, software, hardware, tech trends, and more. My goal is to help you navigate the digital world in a simple and entertaining way.