Monday, November 11, 2013

catch script errors in event log


$error.Clear()
 # ... script does work 
foreach ($errorRecord in $error) { Write-EventLog -LogName psLogs -Source scripts -Message "$($errorRecord | Out-String)" -EventId 0 -EntryType Error }
try-catch
Try { SomeFunction }
Catch {Write-EventLog -LogName psLogs -Source scripts -message $_.Exception.message}
trap [System.Exception] {Write-EventLog -LogName psLogs -Source scripts -Message "$($errorRecord | Out-String)" -EventId 0 -EntryType Error}  source

Use PowerShell to create my own event log

One of the cool things to do with Windows PowerShell is to create my own event logs. Here, I am talking about an event log that is like one of the traditional event logs (traditional event logs are System, Security, and Application). By using Windows PowerShell, these traditional types of event logs are easy to read, easy to write to, easy to back up, and easy to clear.

Use PowerShell to create an event log    source

I use the New-EventLog cmdlet to create a new event log. To use this cmdlet, I need three things:
  1. Open the Windows PowerShell console with admin rights—an error occurs when attempting to create a new event log without elevated rights.
  2. I need the name for the log.
  3. I need to specify a source for the events that write to the log.
The following command creates a new traditional event log named ScriptingGuys with a source named scripts
New-EventLog -LogName ScriptingGuys -Source scripts
When the command runs, no output appears to the Windows PowerShell console. To ensure the command actually created a new event log, I use the Get-EventLog cmdlet with the –List parameter. Here is the command and the associated output.
10:06 C:\> Get-EventLog -List
  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  20,480      0 OverwriteAsNeeded      18,504 Application
  20,480      0 OverwriteAsNeeded           0 HardwareEvents
     512      7 OverwriteOlder              0 Internet Explorer
  20,480      0 OverwriteAsNeeded           0 Key Management Service
  10,240      0 OverwriteAsNeeded           4 Lenovo-Customer Feedback
     512      7 OverwriteOlder              2 Lenovo-Lenovo Patch Utility/Admin
     128      0 OverwriteAsNeeded          30 OAlerts
     512      7 OverwriteOlder              0 ScriptingGuys
                                              Security
  20,480      0 OverwriteAsNeeded      21,437 System
  15,360      0 OverwriteAsNeeded      10,059 Windows PowerShell

Configuring my event log

One of the things I notice when I check the ScriptingGuys event log is that it is set to 512 KB, and it will retain entries for 7 days when it will begin deleting older events. This is not the behavior I want. What I want is for the log to be 64 KB in size and to overwrite as needed. To do this, I would think that I use the Set-EventLog cmdlet—but no, there is not such a thing. The cmdlet is named Limit-EventLog. Looking at the Help, it appears there is only one parameter set. Well, I want toOverWriteAsNeeded, so I guess I also need to set a retention days of 0. I craft the following command, but as you can see, it fails.
10:19 C:\> Limit-EventLog -OverflowAction OverWriteAsNeeded -RetentionDays 0 -Maximum
Size 64KB
Limit-EventLog : Cannot validate argument on parameter 'RetentionDays'. The 0 argument is less than the minimum allowed range of 1. Supply an argument that is greater than or equal to 1 and then try the command again.
At line:1 char:65
+ Limit-EventLog -OverflowAction OverWriteAsNeeded -RetentionDays 0 -MaximumSize
+                                                                 ~
    + CategoryInfo          : InvalidData: (:) [Limit-EventLog], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell
   .Commands.LimitEventLogCommand
Major bummer. Ok, so I try it without the RetentionDays parameter … and it works.
Limit-EventLog -OverflowAction OverWriteAsNeeded -MaximumSize 64KB -LogName scriptingguys
I now use Get-EventLog to confirm my changes took place … the output below confirms that the command worked properly.
10:23 C:\> Get-EventLog -list | ? log -eq scriptingguys
  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
      64      0 OverwriteAsNeeded           0 ScriptingGuys

I can’t get an event log without entries

Interestingly enough, I cannot get an event log that has no entries in it … at least not yet. Because if I use the Get-EventLogcmdlet to attempt to retrieve the ScriptingGuys event log, an error appears. The command and error are here.
10:23 C:\> Get-EventLog -LogName scriptingguys
Get-EventLog : No matches found
At line:1 char:1
+ Get-EventLog -LogName scriptingguys
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-EventLog], ArgumentException
    + FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Comman
   ds.GetEventLogCommand

Writing to the event log

To write to my new event log, I need to specify the following information:
  1. The log name (scriptingguys in my example)
  2. The source (scripting in my case)
  3. EventID (I generally start with 1)
  4. EntryType (Information, Warning, Error)
  5. Message (this is what I want to log)
In this example, I add a new entry to the ScriptingGuys event log.
Write-EventLog -LogName ScriptingGuys -Source scripts -Message "Dude, it works ... COOL!" -EventId 0 -EntryType information
I can now use the Get-EventLog cmdlet to retrieve the event. This is shown here.
10:27 C:\> Get-EventLog -LogName scriptingguys
   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
       1 Jan 29 10:27  Information scripts                         0 Dude, it wor...
That is all there is to using Windows PowerShell to create and to manage event logs. Join me tomorrow when I will talk about more cool stuff.

No comments:

Post a Comment