Scripting. Powershell, VMware, Windows, Active Directory & Exchange. All that kind of stuff…..
RSS icon Email icon Home icon
  • PowerShell 2.0: One Cmdlet at a Time #12 Write-EventLog

    Posted on December 2nd, 2009 Jonathan Medd 2 comments

    Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Write-EventLog cmdlet.

    What can I do with it?

    Write an event in a Windows Event Log on a local or remote machine.

    Example:

    Write an Error event into the Application log on Server01 with source CustomApp1, EventID 8750 and Error Message.

    Write-EventLog -computername Server01 -logname Application 
    -source CustomApp1 -eventID 8750 -entrytype Error 
    -message "CustomApp1 has experienced Error 9875"

    How could I have done this in PowerShell 1.0?

    You could have used the .NET System.Diagnostics.EventLog class. Richard Siddaway has put together a great function which uses this class to make it easy to write to the Event Log using PowerShell 1.0.

    function Write-EventLog
    {
    param([string]$msg = "Default Message", [string]$type="Information")
    $log = New-Object System.Diagnostics.EventLog
    $log.set_log("Application")
    $log.set_source("CustomApp1")
    $log.WriteEntry($msg,$type)
    } 

    You can then use the function like this

    Write-EventLog "CustomApp1 has started" "Information" 

    1000 things 1% better!

     

    2 responses to “PowerShell 2.0: One Cmdlet at a Time #12 Write-EventLog” RSS icon

    • Great Tip..But if you dont have event source already created, a error occurs. You can test and after create. The test you send this tip (teste-path) to me.

      if (!(test-path HKLM:\SYSTEM\CurrentControlSet\Services\Eventlog\Application\TestSource))
      {
      [System.Diagnostics.EventLog]::CreateEventSOurce(”TestSource”,”Application”)
      }

      Write-EventLog -computername $env:computername -logname Application -source TestSource -eventID 8750 -entrytype Error -message “CustomApp1 has experienced Error 9875″

    • Nice job – thanks for the interesting feedback!


    Leave a reply