Monday, August 17, 2015

PowerShell - Microsoft's Trident: Part 3, Scripting

PowerShell and Programming

I’ve been examining the three facets of PowerShell that make it such a powerful and useful tool in the hands of the Windows system admin. In this first post I talked about the shell and its ability to plumb the depths of .NET. In the second post I discussed what makes cmdlets so cool and why every kid should want one. In this post we round out our look with…

The Language of PowerShell

Yes, even though it is a shell environment and it has a passel of useful cmdlets, it is also a rich programming (well, scripting) language. If you’ve ever written code in Assembler, C, FORTRAN, BASIC, Java or the like, you can appreciate all the goodness that PowerShell as a language has to offer.

1. Functions

Code reuse is a term that gets tossed about in programming circles, but all that it means is to write and debug your code one time and use it over and over again. Not only does this prevent you from “re-inventing the wheel” but it makes your work easier to maintain. Once you know something works you just keep using it.
To that end PowerShell supports functions, blocks of PowerShell code that can be referred to by name. They look something like this:
function Say-Hello ([String] $Name = 'Anonymous') {
    Write-Host -NoNewLine 'Hello, '
    Write-Host -ForegroundColor Cyan -NoNewLine $Name
    Write-Host '.'
}
This creates a silly little function named Say-Hello that does just that, but in color. However, once we tweak this function to get it to work just the way we want it, all we have to do is call it:
Say-Hello Dave
Now we can drop this function call in anywhere we want to, as long as the function has been defined. Of course, if we want to use it in multiple scripts we really don’t want to have to copy and paste the function into all of them, so that brings us to…

2. Libraries

Libraries are files, PowerShell scripts, that generally contain nothing but definitions: variables and aliases sometimes, but mostly functions. When your script uses a library it can inherit all the names that were defined in that library. Libraries make it easy to write portable functions that may be used anywhere, and that’s what code reuse is all about.
PowerShell supports two different mechanisms for using libraries. You can load any PowerShell script into another using the dot operator to “source” the file, just like you can in UNIX shells:
. $HOME/myScriptsDir/myLibrary.ps1
Note the space after the dot, because it is a command.
If the library has been saved as a module, that is, with a .psm1 extension, it can be managed through PowerShell’s module system and loaded with a cmdlet:
Import-Module $HOME/myScriptsDir/myLibrary.psm1
Modules and dot-sourced scripts each have a place, but both allow you to create libraries of useful functions and easily use them over and over again.

3. Flow Control

Any programming or scripting language is arguably only as strong as its support for flow control, the ability to suddenly change direction at run time when the situation demands it. PowerShell has several tools for creating scripts that can respond to changing circumstances.
  • Comparison Operators
    PowerShell contains a fairly rich set of comparison operators and can perform all kinds of tests to see if certain conditions have been met.
  • Branching Constructs
    Sometimes you need a script to execute different instructions depending on some condition. PowerShell supports both if and switch keywords for branching to different parts of the script based on useful comparison results.
  • Iteration (a.k.a, Looping)
    PowerShell has five different looping constructs built in to the language, not to mention an iterative cmdlet. There are many ways to repeat tasks in PowerShell.

4. Exception Handling

One of the beauties of PowerShell is that is has not one, but two mechanisms for exception handling. The trap keyword creates global error handlers that can be used to create a default behavior should any part of your script throw an exception. The try..catch construct can deal with errors at very specific parts of your script, giving you the flexibility to handle the same error in different ways depending on where in the execution it occurs.
These can each be used alone or combined together in the same script. Each has its strengths and addresses slightly different challenges for dealing with errors, but both give you the tools to ensure that exceptions are caught and dealt with in your PowerShell scripts.

Really, PowerShell is a feature-rich language with first-class tools that allow you to write really useful administrative scripts. Of course, what would you expect from the company that brought BASIC to the Altair 8800?
Be seeing you.

No comments:

Post a Comment