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 ...

Get Windows Server 2012 Automation with PowerShell Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.