Monday 23 February 2009

New-CustomEventLog.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Creates a new Event Log 
  4. .DESCRIPTION 
  5.     This script first checks to see if a log called NewPSHLog exists. if not, it creates 
  6.     it then exits. if the log exists, the script writes an entry ot the log and then 
  7.     displays the log entries. A separate script clears and deletes the log! 
  8. .NOTES 
  9.     File Name  : New-CustomEventLog.ps1 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell V2 CTP3 
  12. .LINK 
  13.     Script posted to:
  14.     http://www.pshscripts.blogspot.com 
  15. .EXAMPLE 
  16.     First time the script runs: 
  17.     PSH [C:\foo]: .\New-CustomEventLog.ps1' 
  18.     CreatedEventSource 
  19.     Exiting, execute the script a second time to use the source. 
  20.      
  21.     Second time the script runs: 
  22.     PSH [C:\foo]: .\New-CustomEventLog.ps1' 
  23.     PowerShell Eventlog exists 
  24.  
  25.        Index Time          EntryType   Source      InstanceID Message 
  26.        ----- ----          ---------   ------      ---------- ------- 
  27.           12 Feb 22 16:11  Information NewPshLog            0 Writing to new PowerShell even... 
  28. #> 
  29.  
  30. ### 
  31. # Start of Script 
  32. ### 
  33.  
  34. if (![system.diagnostics.eventlog]::SourceExists("NewPSHLog"))  { 
  35.  
  36. # An event log source should not be created and immediately used. 
  37. # There is a latency time to enable the source, it should be created 
  38. # prior to executing the application that uses the source. 
  39. # So let's execute this sample a second time to use the new source. 
  40.             [system.diagnostics.EventLog]::CreateEventSource("MySource", "NewPSHLog"
  41.             "CreatedEventSource" 
  42.             "Exiting, execute the script a second time to use the source." 
  43. # The source is created.  Exit the application to allow it to be registered. 
  44.             return 
  45. else
  46. "NewPSHLog Eventlog exists" 
  47.  
  48. # With log created, create an EventLog instance and assign its source. 
  49. $mylog = new-object System.diagnostics.Eventlog 
  50. $myLog.Source = "NewPshLog" 
  51.  
  52. # Write an informational entry to the event log.     
  53. $myLog.WriteEntry("Writing to new PowerShell event log."
  54.  
  55. # Display log events 
  56. get-eventlog "NewPSHLog" 
  57. # End of Script 

3 comments:

shaneo said...

Excellent! I googled around for a bit before finding this page that answered every question I had (and more)!

Thanks for posting this -- I've added your blog as a bookmark for future reference.

Shane O.

Thomas Lee said...

Glad it helped - sorry the Google results were't easier for you!

Suggestions for other scripts, most welcome.

Coffee_fan said...

Nice post, thanks. The New-EventLog command does this nowadays, however it is not properly documented anywhere how to use it and this post helped.