How to validate PowerShell input and avert problems

Like any other programming language, PowerShell can take action based on user input. The flip side to this, however, is that it’s hugely important to make sure that any human input is correct. There can be dire consequences of executing a script based on input that has not been validated. Thankfully, there are several different techniques that you can use to validate a user’s input before taking action on it.

Did the user enter something?

One of the simplest things that you can do is to make sure that the user has actually entered something, rather than simply pressing the Enter key at an input prompt. You can do this by using either the ValidateNotNull or the ValidateNotNullOrEmpty validation attributes.

You can see an example of how the ValidateNotNullOrEmpty attribute is used in the code sample below. Here, I have created a function called validate. The script body asks for a value, which it stores in a variable called $Value. The variable is then passed to the function. The function declares that the value must be a string and that the parameter is mandatory. It also checks to see if the value is null or empty. If the value is null or empty, the function throws an error. Otherwise, it is allowed to continue running, although it does not do anything else. Here is the code:

Function Validate {
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Value
)
}
$Value = Read-Host "Please enter a value"
Validate $Value

Is the input the required length?

There are any number of ways that we can build onto this technique. Another common validation technique is to make sure that the input is of the required length. For example, maybe for whatever reason, you know that the input should be at least three characters in length, but should not be longer than five characters in length. You can perform such a validation by using the [ValidateLength] parameter and specifying the maximum and the minimum length.

The attribute that is used to do this is ValidateLength. The attribute is followed by the minimum length and the maximum length, separated by a comma. If for example, the input needed to be at least three characters long, but no more than five characters long, then the attribute would look like this:

[ValidateLength(3,5)]

Here is what ValidateLength looks like when combined with the remainder of the script:

Function Validate {
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidateLength(3,5)]
[String[]]$Value
)
}
$Value = Read-Host "Please enter a value"
Validate $Value

Does it adhere to an expected format?

Perhaps the coolest and potentially most useful thing that you can do with PowerShell input validation is to make sure that input adheres to an expected format. Sure, we have already been doing that, at least to a point, but we can take it further.

This morning I received an email message from a friend in Canada. She said that she was mailing me some memory cards and wanted me to have the tracking number. The tracking number consisted of the letters EM, nine numeric digits, and the letters CA (indicating that the package originated in Canada). If I were to create a PowerShell script to track Canadian packages, I could actually validate the input to make sure that it conforms to this very specific format. The attribute that is used for this is ValidatePattern.

ValidatePattern allows you to specify exactly what should be in each position. Enclosing A-Z in brackets, for example, indicates that the position can accept a letter. On the other hand, using \d indicates that the position can only hold a digit.

ValidatePattern also lets you take some shortcuts. Enclosing a number inside of braces {} allows you to specify the number of positions that should be occupied by letters or numbers. For example [A-Z]{10} would indicate that the input should contain a string of ten letters.

So, let’s put this to work on a Canadian postage tracking number. Let’s assume that the position containing the letters EM could contain any two letters (I don’t know how it works in real life). This position should be followed by nine numbers and then the letters CA.

We can define the two letters as [A-Z]{2}. Similarly, the nine numbers can be defined as \d{9}. Since the last two positions need to be filled by very specific characters (CA), we can define these two positions as [C][A]. Here is what the string looks like as a whole:

[ValidatePattern("[A-Z]{2}\d{9}[C][A]")]

Here is what the validation looks like when combined with the rest of the script:

Function Validate {
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidatePattern("[A-Z]{2}\d{9}[C][A]")]
[String[]]$Value
)
}
$Value = Read-Host "Please enter a value"
Validate $Value

As you look at the code shown above, you will notice that I am no longer validating the input length. While I doubt that PowerShell would give you any problems if you did attempt to validate the length, there is no reason to check the length if you are specifying what every position within the input should be.

Checking for specific values

One last thing that I want to show you is how to validate the input to check for specific values. In the previous example, I showed you how to validate a Canadian tracking number. But what if the tracking number could have potentially been from any country in North America? If that is the case, then country codes such as CA, US, or MX might be acceptable.

What we can do in that sort of situation is to replace [C][A] (which I actually could have shortened to [CA]) with the possible values that could go in that position. This means that [C][A] would be replaced by [CA,US,MX] Here is what the code looks like:

Function Validate {
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidatePattern("[A-Z]{2}\d{9}[CA,MX,US]")]
[String[]]$Value
)
}
$Value = Read-Host "Please enter a value"
Validate $Value

So in this case, the script expects a tracking number that starts with two letters, followed by nine numbers, and then a country code of CA, US, or MX.

Many ways to validate PowerShell input

As you can see, there are lots of different techniques that you can use to validate PowerShell input. It is worth noting that I have limited my sample scripts to validating a single parameter, but you can just as easily validate multiple parameters. You simply need to separate the parameter validations with a comma.

Featured image: Pixabay

Leave a Comment

Your email address will not be published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top