New-EventLog

Getting Started with New-EventLog in PowerShell

Welcome back to Wahmans PowerShell blog! Today, we are going to dive into an essential cmdlet that allows you to take control over Windows event logs: New-EventLog.

Event logs are vital for monitoring events and troubleshooting on Windows machines. The New-EventLog cmdlet allows you to create custom event logs and event sources on either local or remote computers. This opens up opportunities for administrators and developers to log events from their own scripts or custom applications.


What does New-EventLog Do?

According to Microsoft:

Creates a new event log and a new event source on a local or remote computer.

This empowers you to create your own event log names (like “MyScriptLog”) and then define sources (like “MyApp”) that write events to these logs with Write-EventLog.


Example 1: Create a Simple Event Log (Beginner)

This creates a new event log named MyScriptLog with a source MyApp on your local machine.

New-EventLog -LogName "MyScriptLog" -Source "MyApp"

After this, you can log entries with Write-EventLog and view the log in Event Viewer under “MyScriptLog”.


Example 2: Check and Create If Not Exists (Intermediate)

Before creating a log, you should check if it already exists to prevent errors.

if (-not [System.Diagnostics.EventLog]::SourceExists("MyApp")) {
    New-EventLog -LogName "MyScriptLog" -Source "MyApp"
}

This avoids the “source already exists” error that can occur when the log or source already exists on the system.


Example 3: Creating a Log on a Remote Computer (Advanced)

If you have administrative rights, you can create an event log on a remote machine like this:

New-EventLog -ComputerName "RemotePC01" -LogName "AuditLog" -Source "AuditScript"

Make sure that remoting is enabled and proper permissions are set on the target machine.


Example 4: Automate Event Log Setup for Deployment (Advanced)

Use a function to automate creation of logs and sources during deployments.

function Ensure-EventLog {
    param(
        [string]$LogName,
        [string]$Source
    )
    
    if (-not [System.Diagnostics.EventLog]::SourceExists($Source)) {
        New-EventLog -LogName $LogName -Source $Source
        Write-Host "Created event log '$LogName' with source '$Source'."
    } else {
        Write-Host "Event source '$Source' already exists."
    }
}

# Usage
Ensure-EventLog -LogName "DeploymentLogs" -Source "DeployScript"

This is useful in CI/CD pipelines or startup scripts to ensure consistent logging setup across environments.


Important Notes

  • You must have administrative privileges to create a new event log.
  • Only one source can be associated with one log at a time.
  • Make sure to document and clean up unused logs and sources over time.

That’s it for today!

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *