Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Windows Server 2012 Automation with PowerShell Cookbook

You're reading from   Windows Server 2012 Automation with PowerShell Cookbook If you work on a daily basis with Windows Server 2012, this book will make life easier by teaching you the skills to automate server tasks with PowerShell scripts, all delivered in recipe form for rapid implementation.

Arrow left icon
Product type Paperback
Published in Mar 2013
Publisher Packt
ISBN-13 9781849689465
Length 372 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
EDRICK GOAD EDRICK GOAD
Author Profile Icon EDRICK GOAD
EDRICK GOAD
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

Windows Server 2012 Automation with PowerShell Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Understanding PowerShell Scripting 2. Managing Windows Network Services with PowerShell FREE CHAPTER 3. Managing IIS with PowerShell 4. Managing Hyper-V with PowerShell 5. Managing Storage with PowerShell 6. Managing Network Shares with PowerShell 7. Managing Windows Updates with PowerShell 8. Managing Printers with PowerShell 9. Troubleshooting Servers with PowerShell 10. Managing Performance with PowerShell 11. Inventorying Servers with PowerShell 12. Server Backup Index

Validating parameters in functions


Whenever a script or program receives data from an unknown source, the general rule is that the data should be validated prior to being used. Validation can take many forms, with simple validations such as confirming the value exists, is of the right type, or fits a predefined format. Validation can also be complex multi-stage events such as ensuring a username exists in a database before prompting for a password.

This section will review several basic validation-testing methods for use in PowerShell.

How to do it...

Here we will discuss creating a function without input validation:

  1. Create a basic function with no input validation:

    Function Hello-World
    {
        param($foo)
        "Hello $foo"
    } 
  2. Test the function using different input types.

    Update the function to perform input type validations as discussed in the following steps:

  3. Update the function to include the basic string validation.

    Function Hello-WorldString
    {
        param([string] $foo)
        "Hello $foo"
    }
  4. Test the function using different input types:

  5. Update the function to perform basic integer validation.

    Function Hello-WorldInt
    {
        param([int] $foo)
        "Hello $foo"
    }
  6. Test the function using different input types:

  7. Update the function to perform basic float validation.

    Function Hello-WorldFloat
    {
        param([float] $foo)
        "Hello $foo"
    }
  8. Test the function using different input types:

  9. Update the function to perform basic array validation.

    Function Hello-WorldStringArray
    {
        param([string[]] $foo)
        "Hello " + $foo[0]
    }
  10. Test the function using different input types:

Update the functions to perform validation of input values:

  1. Create a function to validate the length of a parameter:

    function Hello-WorldLength{
        param([ValidateLength(4,10)] $foo)
        "Hello $foo"
    }
  2. Test the function using different input types:

  3. Create a function to validate a number in a range:

    function Hello-WorldAge{
        param([ValidateRange(13,99)] $age)
        "Hello, you are $age years old"
    }
  4. Test the function using different input types:

  5. Create a function to validate a set of parameters:

    function Hello-WorldSize{
        param([ValidateSet("Skinny", "Normal", "Fat")] $size)
        "Hello, you are $size"
    }
  6. Test the function using different input types:

  7. Create a function that validates against a script:

    function Hello-WorldAge2{
        param([ValidateScript({$_ -ge 13 -and $_ -lt 99})] $age)
        "Hello, you are $age years old"
    }
  8. Test the function using the different input types:

  9. Create a function to validate the input as a phone number:

    Function Test-PhoneNumber
    {
        param([ValidatePattern("\d{3}-\d{4}")] $phoneNumber)
        Write-Host "$phoneNumber is a valid number"
    }
  10. Execute the Test-PhoneNumber function using different input types:

Use custom validation to test parameters inside our function:

  1. Update the function to use custom validation internal to the script with regular expressions:

    Function Test-PhoneNumberReg
    {
        param($phoneNumber)
        $regString=[regex]"^\d{3}-\d{3}-\d{4}$|^\d{3}-\d{4}$"
        if($phoneNumber -match $regString){ 
            Write-Host "$phoneNumber is a valid number"
        } else {
            Write-Host "$phoneNumber is not a valid number"
        }
    }
  2. Test the function using different input types:

How it works...

We start off with a simple Hello-World function with no input validation. Three different calls to the function are performed, one with a username (as the function was designed to work), one with a number, and yet another without any parameters. As you can see, all three commands complete successfully without returning errors.

In the first group of functions in the steps 3 to 10, we see a set of examples using Type Validation to confirm the parameters are of a specific type. There are four iterations of the Hello-World example that accept a string, integer, float, and array as inputs. As you see from the calls to Hello-WorldString, both text and numbers are viewed as strings and return successfully. However, the calls to Hello-WorldInt succeed when a number is passed, but fail when text is passed.

Note

You may notice that the original number 867.5309 passed to the function Hello-WorldInt was rounded and truncated when returned. This is because integers are whole numbers—that is, not partial numbers. When the number was cast as an integer, it was rounded to the nearest whole value, which in this case caused it to round up to 868.

In the second set of functions in steps 11 to 20, we see a set of examples using basic input validation. These functions use ValidateLength, ValidateRange , ValidateSet , ValidateScript , and ValidatePattern attributes of the parameters to validate the input. Additionally, these validation types can be used in conjunction with the basic type validations to further ensure the input is of the correct type and value.

The last set of examples in steps 21 to 24 perform validation internal to the script, instead of relying on the in-built validation. The function named Test-PhoneNumberReg uses a regular expression in order to validate the input as part of the script. Instead of relying on validation using types or ValidatePattern, this function simply passes the variable to the PowerShell code in order to check the input. By managing the validation as part of the function, we have more flexibility on how we handle and present validation errors to our users, and can return a more user-friendly message to the end user.

There's more...

It is considered a best practice to perform at least basic validation for all inputs. Lack of input validation can result in the function crashing, operating unpredictably, or even resulting in damaging data in your environment. This has been a common method for computer attackers to access secure systems and should be taken diligently.

See also

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image