While Loop with multiple conditions displaying incorrect message

Welcome Forums General PowerShell Q&A While Loop with multiple conditions displaying incorrect message

Viewing 3 reply threads
  • Author
    Posts
    • #275148
      Participant
      Topics: 1
      Replies: 1
      Points: 14
      Rank: Member

      Hello Guys
      This script prompts a user for input values 0 or 1 or 2. if the user input doesn’t equal to 0 or 1 or 2 then an error message will be displayed “Incorrect option selected”. But when I execute the script the user inputs equal 0 or 1 or 2 the “Incorrect option selected” error message is displayed instead of displaying a message for the option that the user selected. Can someone please review my code below and help me figure this out. I used PowereShell ISE and Visual Studio Code and got the same result. Thanks in advance.

      • This topic was modified 1 month, 3 weeks ago by Mighty34.
    • #275370
      Participant
      Topics: 17
      Replies: 1951
      Points: 3,988
      Helping Hand
      Rank: Community Hero

      Rather than checking each variable, it’s a bit more straight forward create an array and see if the value is in the array with contains\notcontains. Also, take it easy on the comments, almost every thing you commented on could be easily read in the code. Use comments sparingly to indicate something that is not obvious in the code or logic:

    • #275385
      Participant
      Topics: 4
      Replies: 427
      Points: 756
      Helping Hand
      Rank: Major Contributor

      Your problem is that this line

      if (($select -ne 0) -or ($select -ne 1) -or ($select -ne 2))

      will always return True because of the way the -or operator works.  If any of the statements are True then the -or operator will return True.

    • #275388
      Participant
      Topics: 1
      Replies: 1
      Points: 14
      Rank: Member

      Rather than checking each variable, it’s a bit more straight forward create an array and see if the value is in the array with contains\notcontains. Also, take it easy on the comments, almost every thing you commented on could be easily read in the code. Use comments sparingly to indicate something that is not obvious in the code or logic:

      <link rel=”stylesheet” type=”text/css” href=”https://powershell.org/wp-content/plugins/urvanov-syntax-highlighter/themes/powershell-ise/powershell-ise.css”&gt;
      <link rel=”stylesheet” type=”text/css” href=”https://powershell.org/wp-content/plugins/urvanov-syntax-highlighter/fonts/liberation-mono.css”&gt;

      This worked :)!!!.Thanks a lot. Do you have a possible reason why my code didn’t work. I just need some clarification so I will know better for next time.
      sorry about the comments its a probably a bad habit that i use to keep track about that i doing or intend to do.

Viewing 3 reply threads
  • You must be logged in to reply to this topic.