PowerShell Basics: How to Validate the Length of an Integer


Recently I fielded the following PowerShell question:

How do I make sure a variable, which is an int, is of a certain length?”

Turns out it’s not too hard as the solution simply requires the use of a little regex. Consider the following example:

 

[int]$v6 = 849032
[int]$v2 = 23
$v6 -match '^\d{6}$'
$v2 -match '^\d{6}$'

$v6 is an int that is six digits long. $v2 is an int that is only two inches long. Lines three and four test to see if each variables match the pattern ‘^\d{6}$’ which is regex speak for “start of the line, any digit, and six of them, end of the line”. The first one will be true, because it’s six digits, and the second one will be false. You could also use something like ‘^\d{4,6}$’ to validate that the int is between four and six digits long.

PowerShell_Tips_Tricks_thumb.png

Comments (0)

Skip to main content