Validate A Variable
Powershell

when you want to wait for user input and place that input into a variable, you might want to validate that data that has been entered.

Let's say you want as input an email address but the user types b.henderson@microsoft that is not a valid email address
So let's make it to validate that variable

$email = "b.henderson@powershell.com"
$v = Get-Variable email
$pattern = "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b"
$v.Attributes.Add($(New-Object `System.Management.Automation.ValidatePatternAttribute `-argumentList $pattern))

So that
$email = "moc.liame|dilav#moc.liame|dilav"
$email = "invalid@email"

So when you only want purple, blue and yellow as input

$option = "purple"
$v = Get-Variable option
$v.Attributes.Add($(New-Object `
  System.Management.Automation.ValidateSetAttribute `
  -argumentList "purple", "blue", "yellow"))
$option = "purple"
$option = "blue"
$option = "black"

The last value will create an error

On Me

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License