jshizzle
jshizzle

Reputation: 487

Validate against an array

I'm trying to setup a validation check against an array. I have the following

$ValidDomain = "*.com","*.co.uk"
$ForwardDomain = Read-Host "What domain do you want to forward to? e.g. contoso.com"
#while (!($ForwardDomain -contains $ValidDomain)) {
while (!($ValidDomain.Contains($ForwardDomain))) {
    Write-Warning "$ForwardDomain isn't a valid domain name format. Please try again."
    $ForwardDomain = Read-Host "What domain do you want to forward to? e.g. contoso.com"
}

The commented while line is just an alternative way I've been testing this.

If I enter, when prompted by Read-Host, "fjdkjfl.com" this displays the warning message rather than saying it's valid and keeps looping.

I have tried using -match instead of -contains but get the message:

parsing "*com *co.uk" - Quantifier {x,y} following nothing.

Have I got this completely wrong?

Upvotes: 0

Views: 722

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200573

Contains() and -contains don't work the way you expect. Use a regular expression instead:

$ValidDomain = '\.(com|co\.uk)$'
$ForwardDomain = Read-Host ...
while ($ForwardDomain -notmatch $ValidDomain) {
    ...
}

You can construct $ValidDomain from a list of strings like this:

$domains = 'com', 'co.uk'
$ValidDomains = '\.({0})$' -f (($domains | ForEach-Object {[regex]::Escape($_)}) -join '|')

Regular expression breakdown:

  • .: The dot is a special character that matches any character except newlines. To match a literal dot you need the escape sequence \..
  • (...): Parentheses define a (capturing) group or subexpression.
  • |: The pipe defines an alternation (basically an "OR"). Alternations are typically put in grouping constructs to distinguish the alternation from the rest of the expression.
  • $: The dollar sign is a special character that matches the end of a string.

The {0} in the format string for the -f operator is not part of the regular expression, but a placeholder that defines where (and optionally how) the second argument of the operator is inserted into the format string.

Upvotes: 2

Related Questions