Posey's Tips & Tricks

How To Validate Input in PowerShell Functions, Part 1

If your automated script takes action based on a value, it's critical to make sure the value is correct. Good thing PowerShell has ways to validate the values that are passed to a function.

In recent years, I have found that nearly all of the PowerShell scripts that I have written for production use have required me to pass values to functions within the script.

If you are creating an automated script that takes action based on a value that it receives, then it is really important to make sure that the value is correct. Otherwise, there is no telling what the script might do.

Thankfully, PowerShell provides some ways of validating the values that are passed to a function.

If I am to be completely honest with you, then I have to confess that I do not always use PowerShell's built-in validation. Sometimes, instead, I opt to do something like this:

If ($Value -LT 100)
	{
	Do-Something
	}

In this example, the script would check to see if a variable named $Value contained a numerical value that is less than 100 and, if so, it launches a function called Do-Something.

The disadvantage to validating values this way is that it can make your scripts more complicated. Not only do you have to write the code to check to make sure that your values are within an acceptable range, but you can end up having one function call another function (just as I have done here), and that function may in turn end up calling yet another function.

The advantage of handling validation in this way, however, is that it allows out-of-range values to be handled cleanly. Suppose, for example, a value was passed to a function and a series of if statements like the one shown above found that the value was not within an acceptable range. You could write the code in such a way that it would display a warning message, and then call a function that asks the user to enter a new value.

In contrast, PowerShell does have native validation capabilities. I sometimes use those capabilities. The advantage to doing so is that validating input in this way is simple. The disadvantage is that unless you do something to handle errors, an out-of-range value will cause the script to crash. Let me show you how this works.

Since I have always been a fan of spicy foods, I created a really simple function that I am calling Salsa. The function accepts one input parameter called Spice. The script then checks to make sure that the spice level is either medium, hot or extra hot. As long as the spice level meets the validation criteria, the function displays the spice level. Here is what the function looks like:

Function Salsa 
{ 
    Param( 
        [ValidateSet("Medium","Hot","Extra Hot")] 
        [String] 
        $Spice
	) 

 write-host "The Salsa is " $Spice

}

Salsa -Spice Hot

As you can see, the very last line calls the Spice function and passes it a value of Hot. The ValidateSet line within the function checks to see if the value is Medium, Hot or Extra Hot. In this case, the value meets the criteria, so the function displays a line of text that says:

The Salsa is Hot.

You can see the output in Figure 1.

Figure 1: The function displays the spice level of the function.

OK, so let's change the spice level to Mild, which is not allowed by the function's validation. When I run the script again, the function generates a PowerShell error message. You can see the error shown in Figure 2.

[Click on image for larger view.] Figure 2: When the spice level does not meet the validation criteria, PowerShell displays an error message.

For the sake of clarification, the error message does not indicate that the script has terminated. It only indicates that the function has been aborted. Let me show you what is actually happening. Here is a slight revision to the script:

Function Salsa 
{ 
    Param( 
        [ValidateSet("Medium","Hot","Extra Hot")] 
        [String] 
        $Spice
	) 

 write-host "The Salsa is " $Spice

}

Salsa -Spice Mild
Write-Host "The script is finished".

The script above is exactly the same as what I showed you before, but with two minor changes. First, the spice level is set to Mild, which causes an error to occur. The other thing that I have done is add a line at the very end of the script that displays text that says "the script has finished." So check out Figure 3, which shows what happens when I run the script.

[Click on image for larger view.] Figure 3: This is what happens when I run the script.

If you look at the code above, you can see that the function displays a line of text that says "the salsa is." That line of text is never displayed in the output, which is a clear indicator that the function is being terminated. On the other hand, the line "the script is finished" is displayed, which indicates that after the function is terminated, the script continues to run from the point at which the function was called.

There is actually quite a bit more that you can do with regard to validation in PowerShell. I will show you some of these techniques in Part 2.

About the Author

Brien Posey is a 22-time Microsoft MVP with decades of IT experience. As a freelance writer, Posey has written thousands of articles and contributed to several dozen books on a wide variety of IT topics. Prior to going freelance, Posey was a CIO for a national chain of hospitals and health care facilities. He has also served as a network administrator for some of the country's largest insurance companies and for the Department of Defense at Fort Knox. In addition to his continued work in IT, Posey has spent the last several years actively training as a commercial scientist-astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space. You can follow his spaceflight training on his Web site.

Featured

comments powered by Disqus

Subscribe on YouTube

Upcoming Training Events

0 AM
Live! 360 Orlando
November 17-22, 2024
TechMentor @ Microsoft HQ
August 11-15, 2025