Often, there is a need to log information when a script runs. Instead of writing log information to a text file that you would have to maintain and manage yourself, you can use the built-in Windows logging system with all of its benefits, too.
To do this, you just need to initialize your own log. This needs to be done once by an Administrator, so launch an elevated PowerShell, and then enter a line like this:
That's it. You now have a log file that can log incidents with the sources "LogonScript", "MaintenanceScript", and "Miscellaneous". You might just want to configure it a bit more and tell the logging system how large the file can grow and what should occur when it runs full:
Now, your new log file could grow as large as 500MB, and entries would be kept for 30 days until they get overwritten by newer entries.
You can now close your elevated shell. Writing to your log file does not require special privileges and can occur from any vanilla script or logon script. So switch to a regular PowerShell console, and try this:
Logging incidents is now a snap, and you can pick any event ID or message you want. You are only limited to the registered event sources.
Using Get-EventLog, you can now easily analyze scripting problems on that machine:
So why take the hassle of logging incidents to plain text files when you can as well use the built-in industrial-strength Windows logging system.