Optimization and standardization of PowerShell scripts

Beautiful Code

Handle Exceptions, Not Errors

When you develop PowerShell scripts, you need to perform an extensive testing phase before the scripts go live. Support is provided by PowerShell modules such as Pester (Get-Help about_Pester). Additionally, debug-level settings can be helpful. To start line-by-line debugging with variable tracking, use:

> Set-PSDebug -trace 2

However, despite careful development, run-time errors can be caused by missing network connections, insufficient privileges, unavailable servers, and so on. To field such errors, you first need to set the ErrorActionPreference variable more strictly. (See also the "Error Handling Checklist" box.) The default value is continue, which only handles critical errors. To classify each error as critical, set the value to stop; then, statement-specific error handling can be used with try/catch/finally.

Error Handling Checklist

The following measures are best practices for error handling:

  • Set $ErrorActionPreference to stop.
  • Use statement-specific error handling with try/catch.
  • Use exit codes.
  • Standardize exit codes (assignments to specific error types in tabular form).
  • Use error logs.

If the application is terminated in response to an error, it is important to assign a value to the exit statement, which can be retrieved with the $LastExitCode environment variable. If the script app is part of a workflow, it could then determine the exit point.

Finally, some hints as to what should not be in a script:

  • The PowerShell already offers a self-documenting approach through the consistent verb-noun principle. This should not be wasted by misleading aliases or positioned or abbreviated parameters.
  • Be careful if you frequently use pipes because overall processing time suffers. A test with Measure-Command gives you clarity quickly.
  • Missing dependency declarations, required host versions, and execution permissions are remedied by #requires (Get-Help about_requires).
  • Commented out code elements as the remnants of a test is simply confusing. To test different approaches, work with branches and versioning tools.

Conclusions

Freedom in scripting is both a blessing and a curse. As soon as scripts assume an important function in the company, standardization becomes mandatory. For the IT manager, the team situation can be nerve-racking with just one scripter, so team play should start with the source code. Comprehensive guidance will increase the quality of your PowerShell scripting and future-proof your scripts.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus