Musings on the splendour of PowerShell
Below is an excerpt from one of the ‘Inside Track’ pieces I wrote for the Microsoft Press Windows PowerShell Best Practices book by Ed Wilson, the Microsoft Scripting Guy.
Why consider script logging? You’ll have to troubleshoot issues with your scripts - I’ve written scripts for enterprise environments for a number of years and have rarely seen a script that works perfectly with the first draft of code. You’ll have to troubleshoot during development, when the script is released into production and, maybe, others will reuse your hard work. To troubleshoot effectively, you need to understand what it was your script did, and that’s where script logging comes in - it’s easier to investigate an issue if you can look at logs created by your scripts. Even if you’re not troubleshooting, script logging can show you what successful changes were made and create a valuable audit trail.
What should your script logging capture? That will depend on what the script does. To start, I suggest the following: user name, computer name, script start time, script finish time, tasks completed and any errors that occur. What file format should be used? That’s another one of the many great things about PowerShell – it’s very easy to write to a text file, a CSV file, a HTML file or an XML file. Those aren’t your only options though – a colleague of mine created a centralised database for script logging, allowing administrators to analyse logs from many scripts – use your imagination!
How can PowerShell help you out? As you'd expect, there are many features that can assist with script logging:
You’ll have to troubleshoot issues with your scripts, so invest time in writing a script logging function – you’ll use it again and again!
And just to prove that point…
For years, I’ve logged script output in a format that can be parsed by the SMS Trace application (part of the SMS 2003 Tool Kit and now superseded by CM Trace). This allows me to match events to script components, highlight key information, filter, search and even look-up error codes.
If you’d like to take a look-see, then my Log-ScriptEvent function can be found here.