Validating Integer Variables

by May 18, 2017

You can easily assign the [Int] type to a variable to make sure it can contain only digits. But did you know that you can also apply a regex validator (at least starting in PowerShell 4)?

This way, you can define that a variable should be integer but can only have numbers between 2 and 6 digits, or any other pattern you require:

 
PS>  [ValidatePattern('^\d{2,6}$')][int]$id = 666
 
PS> $id = 10000
 
PS> $id = 1000000
Cannot check variable id. Value 1000000 is  invalid for variable id.


PS> $id = 10
 
PS> $id = 1
Cannot check variable  id. Value 1 is invalid for variable id.
 

Twitter This Tip! ReTweet this Tip!