PowerShell Training: Switch Parameter Validation
By Gabriel Taylor
Published December 7, 2016
Estimated Reading Time: 6 minutes

Summary

There are many ways to validate the presence of a

[switch]

parameter within a PowerShell script or function, but some are definitely better. This post provides a PowerShell function that demonstrates the results of various validation methods and specifies which methods should be used.

Introduction

PowerShell provides a number of options for both accepting and controlling input for scripts and functions through the use of Parameters. Parameters can be configured to only accept certain types of input, or only certain values, and more. One option is the

[switch]

parameter type.

[switch]

parameters don’t accept input, rather they simply are or are not present – an example would be the

-Verbose

parameter available on all out-of-box cmdlets. We are able to reproduce the same functionality with PowerShell scripts and functions in order to have our scripts take actions only when the parameter is (or isn’t) supplied.

 

To get our scripts to take action based on a

[switch]

parameter’s presence, the script only needs to leverage a small bit of parameter validation around the code that should be optionally executed. This validation takes the form of an

if(){}

statement – specifically, the comparison placed within the parentheses validates the presence of the parameter, while the executable code is placed within the curly braces.

 

There are several different comparison methods which can be used to validate whether or not the

[switch]

parameter was used, and that brings us to the topic of this post. Some methods are definitely better than others. Some of the easiest methods don’t actually ensure that the parameter was provided, others give inconsistent results and can be accidentally hijacked by other code in the script or function. Also, sometimes it is easy to overlook or mis-estimate the way the comparison method will actually be handled by PowerShell. Sometimes we just need a reminder of how PowerShell will handle the code we’ve written, or a reminder of how we should be going about implementing our switch parameter validation.

 

To that end, I wrote a simple PowerShell function that provides a list of different methods of switch parameter validation, illustrates precisely the result achieved by using each method within an

if(){}

statement, and states which methods are good and bad. If you just need a reminder of how PowerShell will handle the validation you’ve implemented, this can be used to visualize the validation’s output. If you are looking for ways to improve your validation, this shows an array of options. Read on to get the code and see the results.

Let’s Start with the Code

Let’s cut to the chase and start off by providing the function itself, after which we will walk through how it works. Below you’ll find the function:

 

<#
    .SYNOPSIS
    A simple function used to demonstrate Switch parameter validation techniques

    .DESCRIPTION
    A simple function used to demonstrate the good and bad ways to validate a Switch parameter's existence.

    .EXAMPLE
    validateSwitchParam

    This example shows the resulting values for different statements when the switch parameter is not supplied.

    .EXAMPLE
    validateSwitchParam -switchParam

    This example shows the resulting values for different statements when the switch parameter is supplied.

    .NOTES
    Written by Gabriel Taylor, 2016
#>
function validateSwitchParam
{
    param
    (
        [switch]
        $switchParam
    )

    # Define a function to create our output objects
    function createResultObject
    {
        param
        (
            [string]
            $Rating,

            [string]
            $IfComparison,

            [string]
            $ComparisonResult
        )

        # Define the new object
        $outputObject = New-Object -TypeName psobject -Property ([ordered]@{
            "Method_Rating" = $Rating
            "If_Comparison_Logic" = $IfComparison
            "Comparison_Result" = $ComparisonResult
        })

        # Return the object
        Write-Output -InputObject $outputObject
    }

    # Create an array to store the test results
    [object[]]$outputArray = @()

    # BAD - the bad strategy
    $outputArray += createResultObject -Rating "BAD" 
        -IfComparison "$switchParam" 
        -ComparisonResult $switchParam

    # OKAY - This is what happens when you use this in an If statement and explicitly declare -eq $true; it's exactly what you'd want
    #     This is only "Okay" because you've no way of validating the switch was supplied as a parameter and that the variable wasn't 
    #     explicitly written in the script somewhere.
    $outputArray += createResultObject -Rating "OKAY" 
        -IfComparison "$switchParam -eq $true" 
        -ComparisonResult ($switchParam -eq $true)

    # OKAY - This is what happens when you use this in an If statement and explicitly declare -eq $false; it's exactly what you'd want
    #     This is only "Okay" because you've no way of validating the switch was supplied as a parameter and that the variable wasn't 
    #     explicitly written in the script somewhere.
    $outputArray += createResultObject -Rating "OKAY" 
        -IfComparison "$switchParam -eq $false" 
        -ComparisonResult ($switchParam -eq $false)

    # GOOD - This is good, do this to validate the parameter existence
    $outputArray += createResultObject -Rating "GOOD" 
        -IfComparison "$PSBoundParameters.ContainsKey('switchParam')" 
        -ComparisonResult ($PSBoundParameters.ContainsKey('switchParam'))

    # GOOD - This is what happens when you use this in an If statement and explicitly declare -eq $true; it's exactly what you'd want
    $outputArray += createResultObject -Rating "GOOD" 
        -IfComparison "$PSBoundParameters.ContainsKey('switchParam') -eq $true" 
        -ComparisonResult ($PSBoundParameters.ContainsKey('switchParam') -eq $true)

    # GOOD - This is what happens when you use this in an If statement and explicitly declare -eq $false; it's exactly what you'd want
    $outputArray += createResultObject -Rating "GOOD" 
        -IfComparison "$PSBoundParameters.ContainsKey('switchParam') -eq $false" 
        -ComparisonResult ($PSBoundParameters.ContainsKey('switchParam') -eq $false)

    # BAD - Don't do this alone
    $outputArray += createResultObject -Rating "BAD" 
        -IfComparison "$PSBoundParameters.switchParam" 
        -ComparisonResult ($PSBoundParameters.switchParam)

    # GOOD - Use this in a comparison to validate switch parameter existence (example using $true)
    $outputArray += createResultObject -Rating "GOOD" 
        -IfComparison "$PSBoundParameters.switchParam -eq $true" 
        -ComparisonResult ($PSBoundParameters.switchParam -eq $true)

    # BAD - Don't do this, though, as it will never be $true (example using $false)
    $outputArray += createResultObject -Rating "BAD" 
        -IfComparison "$PSBoundParameters.switchParam -eq $false" 
        -ComparisonResult ($PSBoundParameters.switchParam -eq $false)

    # BAD - Don't do this alone either
    $outputArray += createResultObject -Rating "BAD" 
        -IfComparison "$PSBoundParameters.switchParam.IsPresent" 
        -ComparisonResult ($PSBoundParameters.switchParam.IsPresent)

    # GOOD - Use this in a comparison to validate switch parameter existence (example using $true)
    $outputArray += createResultObject -Rating "GOOD" 
        -IfComparison "$PSBoundParameters.switchParam.IsPresent -eq $true" 
        -ComparisonResult ($PSBoundParameters.switchParam.IsPresent -eq $true)

    # BAD - Don't do this, though, as it will never be $true (example using $false)
    $outputArray += createResultObject -Rating "BAD" 
        -IfComparison "$PSBoundParameters.switchParam.IsPresent -eq $false" 
        -ComparisonResult ($PSBoundParameters.switchParam.IsPresent -eq $false)

    # Return the test results
    Write-Output -InputObject $outputArray
}

 

The function is pretty straightforward: it has a single parameter defined,

$switchParam

, which is used for illustrating what the result is for validating the switch parameter’s presence via various comparison statements. It then proceeds to list and test 12 different methods for validation, building objects to display the method’s structure, the result, and whether or not the method is seen as a good option. Finally, it returns the objects to communicate the results. The code is commented throughout, which contains reasons about why a method should or shouldn’t be used.

How to Use This Function

Using the function is simple – simply run it, with or without the

-switchParam

parameter supplied, to see what the result would be for various validation methods. Every entry in the “If_Comparison_Logic” property is literally the code which would be placed in the

if(){}

statement’s parentheses to produce the result in the “Comparison_Result” property. The “If_Comparison_Logic” value can be copied and pasted directly into an

if(){}

statement’s parentheses to be used.

 

For example, consider the following code:

 

if ($Verbose -eq $true)
{
    # Execute this code
    Write-Verbose -Message "I am a verbose message!"
}

 

In this code, the comparison being used is

$Verbose -eq $true

, as that is the contents of the

if(){}

statement’s parentheses. This matches the function result with the “If_Comparison_Logic” value of “$Verbose -eq $true”.

 

All that is left to do is run the function and view the output. The following two screenshots show what the function outputs when the

[switch]

parameter is and isn’t supplied:

validateSwitchParam Results - No Parameter

validateSwitchParam Results – No Parameter

validateSwitchParam Results - Parameter Supplied

validateSwitchParam Results – Parameter Supplied

Because the function returns objects, we can also filter the output to, for example, only see the Good methods:

validateSwitchParam Results - Good Only

validateSwitchParam Results – Good Only

If you want to confirm that the switch parameter validation method you’ve chosen is going to return a True result, simply run the function with or without the parameter supplied, per your scenario, check the row that matches the logic you used, and see what the value is of the “Comparison_Result” property.

 

If you’re looking for a comparison to use for a script or function you are building, copy the comparison logic from the Good entry that you like best, drop it in your code, and go.

 

Switch parameter validation is as easy as that.

Conclusion

The goal of this post was to present a PowerShell function which illustrates the results of various methods of switch parameter validation and provides examples of optimal methods. This function only took a few minutes to write, but has proven to be a great reminder and also testing tool while writing my scripts and functions; my hope is that it helps you as well. The full function can be found up above; feel free to grab it and use it as needed. Good luck, and happy scripting!

Article By Gabriel Taylor
With over 12 years of experience in the IT industry, Gabriel brings a focus on repeatable processes, solution design, and quality execution to Model’s Project Services practice. He believes the true value of technology is how it enables businesses to gain efficiencies, increase productivity, and achieve their goals. He is proud to work with Model’s team of experts to bring those benefits to Model’s clients.

Related Posts