olly - Fotolia

Tip

These PowerShell script examples help tidy up code

Even the most grizzled scripting veterans might learn some new PowerShell tips and tricks to tighten their automation code or produce clearer error messages.

Some IT professionals who use PowerShell regularly might think they know everything about the scripting language, but they'd be wrong.

PowerShell has many undocumented or lesser-known features. You can use the following PowerShell script examples to uncover some hidden gems that speed up the scripting process and create well-organized code.

Defining a variable in an if statement

A common PowerShell construct is the if statement, which is a piece of conditional logic that enables the scripter to run code depending on a certain condition. The if statement contains an expression to evaluate -- and the code to run -- based on either a Boolean True/False or null/not null outcome.

$foo = 'bar'
if ($foo -eq 'bar') {
    'The foo variable equals bar'
}

A common use of if statements is to test a condition, then use the output of that condition later. For example, this script finds a match of certain colors out of several colors in an array:

$colors = @('Red','Blue','Green')
if ($colors | Where-Object { $_ -in @('Red','Blue')}) {
    $interestingColors = $colors | Where-Object { $_ -in @('Red','Blue')}
    ## Do something with the $interestingColors array
}

Learn the basics of the PowerShell pipeline

The script queries the $colors array twice for the desired elements. To code more efficiently, check for the condition of the elements and capture those elements at the same time. Do this by defining an array inside the if statement.

$colors = @('Red','Blue','Green')
if ($interestingColors = $colors | Where-Object { $_ -in @('Red','Blue')}) {
    ## Do something with the $interestingColors array
}

The if statement evaluates the output of the expression and simultaneously captures the output of that expression into a variable. This eliminates the need to look up elements inside the variable twice.

Use ValidateScript parameter validation to provide better error messages

PowerShell has several ways to evaluate function and script parameters, with the ValidateScript parameter attribute being one of the most versatile. This attribute enables you to run code against the value of the parameter to confirm the value is what you expect. Unless some thought is put into how the code is built, however, the error messages can display confusing messages.

For example, if you have a function that accepts a parameter value of FilePath, this parameter represents the path of a file that is processed inside the function. To prevent problems in the function, use ValidateScript to check that the file exists before continuing. If the code returns True, the function will proceed; otherwise, it will throw an error.

function Set-ThingOnFile {
    param(
        [Parameter(Mandatory)]
        [ValidateScript({Test-Path -Path $_})]
        [string]$FilePath
    )

    ## Do something with $FilePath here
}

When this function runs, it returns an error that isn't user-friendly.

Set-ThingOnFile : Cannot validate argument on parameter 'FilePath'. The "Test-Path -Path $_" validation script for the argument with value "C:\DoesNotExist.txt" did
not return a result of True. Determine why the validation script failed, and then try the command again.

To improve the error message, create your own with an if/then condition and use the throw command to return a better error.

function Set-ThingOnFile {
    param(
        [Parameter(Mandatory)]
        [ValidateScript({
            if (-not (Test-Path -Path $_)) {
                throw "The file [$($_)] was not found. You must provide a valid file path"
            } else {
                $true
            }
        })]
        [string]$FilePath
    )

    ## Do something with $FilePath here
}

Run the script and the error message is more descriptive and easier to understand. It's one of the handier PowerShell script examples to help debug a tricky bit of code.

Set-ThingOnFile : Cannot validate argument on parameter 'FilePath'. The file [C:\DoesNotExist.txt] was not found. You must provide a valid file path

PowerShell script examples simplify code with splatting

Splatting is a useful feature that defines function parameters as a hash table, and then passes that single hash table to the function. Splatting cleans up code considerably and prevents function calls with lots of parameters from trailing off the screen.

$parameters = @{
    Path = 'C:\Folder'
    Force = $true
}

Get-ChildItem @parameters

Splatting cleans up code considerably and prevents function calls with lots of parameters from trailing off the screen.

Let's say we have a script with some conditions that dictate which parameters get passed to this command. If the Get-ChildItem cmdlet gets called multiple times with some common parameters used in each call, then on each call of Get-ChildItem, the script passes multiple parameters.

$commonParams = @{
    Hidden = $true
    Force = $true
    Verbose = $true
}

Get-ChildItem @commonParams -Filter '*.txt' -Recurse

Get-ChildItem @commonParams -Filter '*.pdf' -Depth 2

It would help to splat the other parameters. To do this, define them as hash tables and pass that hash table to the command as we did with the common parameters.

Now that you have picked up some new tricks from these PowerShell script examples for writing cleaner code, find a way to implement them in your environment and update those scripts that could use some sprucing up.

Dig Deeper on Microsoft messaging and collaboration

Cloud Computing
Enterprise Desktop
Virtual Desktop
Close