Read-host validation issues

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Greg Dent Greg Dent 6 months, 2 weeks ago.

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #36007
    Profile photo of Greg Dent
    Greg Dent
    Participant

    Hi all, me again 🙂

    I'm writing a Powershell script to automate promotion of our 2012R2 domain controllers. We had a WISE script which used to do this, but this has grown old and decrepit, with the original author long gone from the company.

    So far, it's been going well. However, there are a couple of places where we need the admin user to provide some input for the script to work properly. This is fine, but I wanted to make sure this part, which is touched by humans, gets validated properly.

    Here's what I have attempted so far, with my limited understanding of the Do/While loop validation cmd's....

    Do {
    $SiteTypeInput = Read-Host "Enter Selection [1/2/3]"
    } While (($SiteTypeInput -ne '1') -or ($SiteTypeInput -ne '2') -or ($SiteTypeInput -ne '3'))
    $ADSiteType = if ($SiteTypeInput -eq "1") {"HUB"} elseif ($SiteTypeInput -eq "2") {"RO"} elseif ($SiteTypeInput -eq "3") {"JS"}
    
    Do {
    $GC = (Read-Host "`nMake this DC a Global Catalogue? [Y/N]").ToUpper()
    } While (($GC -ne 'Y') -or ($GC -ne 'N'))
    
    $IsGC = if ($GC -eq "Y") {"True"} elseif ($GC -eq "N") {"False"}
    

    Unfortunately, this doesn't seem to work as I intended it. Upon debugging, it does seem to work well with a single 'while' condition set, and falls over when I try and add in multiple operators as above.

    There is obviously a better/safer way to do this – most places I have seen recommend using RegEx to carry out the validation. That's the point I pack up and run away 😉 (kidding, Regex does give me a headache though).

    Any help would be appreciated!!

    #36008
    Profile photo of Jonathan Warnken
    Jonathan Warnken
    Participant

    You can do something like this

    Do {
     $GC = (Read-Host "`nMake this DC a Global Catalogue? [Y/N]").ToUpper()
    } While (!($GC -cmatch "[Y,N]"))
    

    This is a case sensitive match for Y or N anything else with go back through the DO

    #36012
    Profile photo of tommymaynard
    tommymaynard
    Participant

    In your first Do-While loop, change -or to -and. Think, "it's not equal to 1, and it's not equal to 2, and it's not equal to 3." -And is inclusive. You can also use regular expressions and condense your code: ($SiteTypeInput -notmatch '^(1|2|3)$'). You can use regular expressions with your second Do-While loop, as well.

    #36510
    Profile photo of Greg Dent
    Greg Dent
    Participant

    Tommy, good spot. Bad logic!

    It works using -and, I've also tried using the RegEx method, which looks a lot nicer.

    Cheers matey!

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.