To log event information directly to the Windows Event Viewer using PowerShell or Command Prompt, you can utilize the Write-EventLog cmdlet. This approach is beneficial for tracking script execution without creating text log files. Here’s how you can do it:
-
Log an Information Event:Use the following command to write an informational entry to the Application log:
Write-EventLog -LogName Application -Source "Application" -EntryType Information -EventID 1 -Message "PS1 Script started"
-
Add a Custom Event Source:If you want to use a separate event source in the log, create one with:
New-EventLog -LogName Application -Source "MyScripts"
Now you can log events with your custom source:
Write-EventLog -LogName Application -Source "MyScripts" -EntryType Warning -EventID 1 -Message "PS1 Script started"
-
Check the Event Viewer:Open the Event Viewer (
eventvwr.msc
), navigate to the Application log, and you should see the new event listed.
Event Types
The EntryType parameter accepts the following types:
Error
Information
FailureAudit
SuccessAudit
Warning
-
Logging from CMD/BAT Scripts:You can also log information via a command prompt script using
eventcreate.exe
:eventcreate /t information /l application /id 1 /d "BAT script started"
-
Creating a Custom Log:If you need a custom log, use:
New-EventLog -LogName CustomPSLog -Source 'MyScripts','PSScript','PSLogonScript','PSSchedScript'
Before writing to it, check if the log exists:
If ([System.Diagnostics.EventLog]::SourceExists('CustomPSLog') -eq $False) { New-EventLog -LogName CustomPSLog -Source "MyScripts"}
After creating the log, ensure it receives at least one event to appear in Event Viewer:
Write-EventLog -LogName CustomPSLog -Source MyScripts -EntryType Information -EventID 1 -Message "Test"
-
Finding Events with PowerShell:To filter and find specific events in your logs, use the
Get-WinEvent
cmdlet:Get-WinEvent -FilterHashtable @{logname='CustomPSLog';id=1} | ft TimeCreated,Id,Message | Select-Object -First 5
Note on PowerShell Core
In PowerShell Core (7.x), the Write-EventLog cmdlet is not available, and you should use New-WinEvent instead, although it requires registering an event provider. For simplicity, it’s advisable to import the management module:
Import-Module Microsoft.PowerShell.Management -UseWindowsPowerShellWrite-EventLog -LogName CustomPSLog1 -Source CustomPSLog -EntryType Information -EventID 1 -Message "Test2"
Make sure to run these commands as an administrator, as only users in the local Administrators group can send events to the event logs created by administrators.