Using the built-in Windows event log architecture for script logging is great, and very simple. Here are the initial steps to prepare logging (requires Administrator privileges):
New-EventLog -LogName PSScriptLog -Source Logon, Installation, Misc, Secret
Limit-EventLog -LogName PSScriptLog -MaximumSize 10MB -OverflowAction OverwriteAsNeeded
You may want to adjust the log name and/or the names of the error sources. These sources can be anything provided it has not yet been assigned to any event log.
Now, every regular user can use the below code to write to the new event log:
Write-EventLog -LogName PSScriptLog -Source Logon -EntryType Warning -EventId 123 -Message "Problem in script $PSCommandPath"
Note how Write-EventLog uses the same logfile and one of the source names that you defined in your first code.
Once your scripts log information to your log file, you can easily search for events or build reports by using Get-EventLog:
PS C:\> Get-EventLog -LogName PSScriptLog -EntryType Error -Message *test.ps1*
ReTweet this Tip!