Often scripts need to log what they do, and PowerShell scripters invest a lot of thought and time on logging information to text files.
As an alternative, you can easily reuse the work invested by Microsoft: PowerShell can use the event log system to log information. To test-drive, create a new event log using the code below. This part requires Administrator privileges (writing to the log does not):
# name for your log
$LogName = 'PowerShellPrivateLog'
# size (must be dividable by 64KB)
$Size = 10MB
# specify a list of names that you'd use as source for your events
$SourceNames = 'Logon','Work','Misc','Test','Debug'
New-EventLog -LogName $LogName -Source $SourceNames
Limit-EventLog -LogName $LogName -MaximumSize $Size -OverflowAction OverwriteAsNeeded
Once the log is in place, any user can write to the log file:
PS> Write-EventLog -LogName PowerShellPrivateLog -Message 'Script Started' -Source Work -EntryType Information -EventId 1
PS> Write-EventLog -LogName PowerShellPrivateLog -Message 'Something went wrong!' -Source Work -EntryType Error -EventId 1
PS> Get-EventLog -LogName PowerShellPrivateLog | ft -AutoSize
Index Time EntryType Source InstanceID Message
----- ---- --------- ------ ---------- -------
2 Jan 30 21:57 Error Work 1 Something went wrong!
1 Jan 30 21:57 Information Work 1 Script Started
-Source must be one of the names that you specified as legal sources when you created the log. One advantage of using this technique is that you can use Get-EventLog to easily analyze your log entries.
Are you an experienced professional PowerShell user? Then learning from default course work isn’t your thing. Consider learning the tricks of the trade from one another! Meet the most creative and sophisticated fellow PowerShellers, along with Microsoft PowerShell team members and PowerShell inventor Jeffrey Snover. Attend this years’ PowerShell Conference EU, taking place April 17-20 in Hanover, Germany, for the leading edge. 35 international top speakers, 80 sessions, and security workshops are waiting for you, including two exciting evening events. The conference is limited to 300 delegates. More details at www.psconf.eu.
ReTweet this Tip!