Validate and restrict input integer length in PowerShell

Sometimes, while getting user input, you may want it to restrict it to certain characters. This may be for various reasons depending upon the situation. While there is no direct cmdlet or function to do this, you can use regex to help you to determine if the input matches certain pattern. For example, let’s consider that we want to restrict integer length input by user to 6 characters. for this, we can use below regex:

^\d{6}$

In action:

  1. Below example is for a valid case, where input is of 6 characters only:
restrict input integer length - valid case
restrict input integer length – valid case
  1. Below example is for a invalid case, where input is less than 6 characters:
restrict input integer length - invalid input case
restrict input integer length – invalid input case

3. Below example is for a invalid case, where one of the input characters is not a integer:

restrict input integer length - invalid input case 2
restrict input integer length – invalid input case 2

We can also use something like:

‘^\d{2,6}$’

to validate that the int is between two and six digits long.

One thought on “Validate and restrict input integer length in PowerShell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s