header
header Register : : Login header
header
divider
menuleft
menuright
submenu
left

[August 25th, 2008] Check the home page regarding PowerShell related news from a brand new sponsor: Idera

While Loop with multiple choices
Last Post 04 Sep 2008 11:15 PM by glnsize. 4 Replies.
Printer Friendly
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
trueblueUser is Offline
New Member
New Member
Posts:5
Avatar

--
04 Sep 2008 06:49 AM  

I'm trying to use a While Loop to prompt for a response.  I want to force the person to type in one response or another.  I can get this to work this way:

while ($favcolor -ne "blue") {$favcolor = Read-Host "What is your favorite color?"}

If the user types anything other than "blue", they get prompted again.

But when I try and use multiple options, it doesn't work.

while ($favcolor -ne ("blue" - or "green" -or "black")) {$favcolor = Read-Host "What is your favorite color?"}

I've tried several different ways of writing this but I can't seem to figure it out.  Am I going about this the right way?  Is there a better way to do it?  I want to be able to have a list of acceptable answers and then use that variable later in the script.

greeoussUser is Offline
New Member
New Member
Posts:2
Avatar

--
04 Sep 2008 11:12 AM  

try something like this:

while ( ("blue","yellow","red") -notcontains $favcolor)
{$favcolor = read-host " favourite color?"}

glnsizeUser is Offline
Basic Member
Basic Member
Posts:101

--
04 Sep 2008 03:19 PM  

Brandon did a good job explaining this on his blog http://bsonposh.com/archives/343

As for your example, I would suggest something a little more...

If you really want a one liner...  -match/notmatch can take a regular exression.  Not only is this faster but it's easier to read!

while ($favcolor -notmatch "(blue|green|black)") {$favcolor = Read-Host "What is your favorite color?"}

If your not tied to a one liner, then I prefer nesting a switch withing the loop. best of both worlds imo.

$favcolor = ""
while ($favcolor -eq "")
{
    switch (Read-Host "What is your favorite color?")
        {
        "blue"  {$favcolor = "blue"}
        "black" {$favcolor = "blue"}
        "green" {$favcolor = "blue"}
        default {Write-Host "Invalid selection, please try again"}
    }
}

hope that helped
~glenn

trueblueUser is Offline
New Member
New Member
Posts:5
Avatar

--
04 Sep 2008 11:01 PM  
Thanks to both of you. Just what I needed.
glnsizeUser is Offline
Basic Member
Basic Member
Posts:101

--
04 Sep 2008 11:15 PM  

np... glad to help

You are not authorized to post a reply.

Active Forums 4.1
right
   
footer Sponsored by Quest Software • SAPIEN Technologies • ShellTools, LLC • Microsoft Windows Server 2008 footer
footer