Chapter 9. The 10 PowerShell scripting commandments

 

James O’Neill

In my view, PowerShell succeeds because it provides a kit of small, general-purpose commands to be linked together to make larger, specific commands. Extending the toolkit is a good thing, and my approach to extending the toolkit can be summarized as “10 commandments” (which I jokingly call cmdments):

1.  Create functions for reuse, scripts for a single task.

2.  Choose names for commands and parameters wisely.

3.  One task, one function: the “DoStuffWith” verb doesn’t exist for a reason.

4.  Build flexibility into parameters.

5.  Ask whether constants are better as defaults for parameters.

6.  Ask “What could I receive?” and “What could I pass on?”

7.  Use Write- and Out- cmdlets properly.

8.  Use comment-based help, and include examples.

9.  Learn to use the Try{} Catch{} scriptblocks; don’t rely on $ErrorActionPreference.

10.  Choose either to support –WhatIf or to restore data.

This chapter will give you more insight into each commandment.

Constructing a sound function

Scripts do a complete job—you can have “Download new pictures from my RSS feed.ps1” as a script that runs as a scheduled job and doesn’t rely on taking user input. Whereas scripts are specific and self-contained, functions do small jobs, like the built-in commands, and add tasks to the shell making them building blocks for scripts. Functions aim to be part of one or more bigger commands.

Select your function name carefully

Output

Parameters

Example: finding duplicate files

Extra tricks for file parameters

Write code for another person to read

Summary

About the author

sitemap