Welcome Forums General PowerShell Q&A Probably Easy

Viewing 5 reply threads
  • Author
    Posts
    • #31317
      Participant
      Topics: 8
      Replies: 10
      Points: 0
      Rank: Member

      Basically I just want to see if the variable (in this case $roomnumber) matches any of the targets I specify (in this case 1,2 and 3). Below is what I tried, and it doesn’t work.

      $roomnumber = 1
      if ($roomnumber -match ‘1’,’2′,’3′) {
      write-output “works”
      }

      I know I could do the following:

      $roomnumber = 1
      if ($roomnumber -eq ‘1’ -or $roomnumber -eq ‘2’ -or $roomnumber -eq ‘3’) {
      write-output “works”
      }

      But I was hoping there would be any easy way to ask from a list like:

      if ($roomnumber -eq 1,13,563,12,2) {

    • #31318
      Participant
      Topics: 0
      Replies: 669
      Points: 0
      Rank: Member

      You could try using the -contains operator

      $rooms = 1,13,563,12,2
      $roomnumber = 563

      PS> $rooms -contains $roomnumber
      True

      PS> $roomnumber = 127
      PS> $rooms -contains $roomnumber
      False

    • #31321
      Participant
      Topics: 4
      Replies: 104
      Points: 82
      Rank: Member

      … and if you prefer doing it the other way arround, you can also use the -in operation

      C:\> $rooms = 1,13,563,12,2
      
      C:\> $roomnumber = 563
      C:\> $roomnumber -in $rooms
      True
      
      C:\> $roomnumber = 127
      C:\> $roomnumber -in $rooms
      False
      
      C:\>
      
    • #31396
      Participant
      Topics: 3
      Replies: 17
      Points: 0
      Rank: Member

      Are these sequential or random numbers or both?
      Does the script do anything besides output true or false for a match?

    • #31420
      Participant
      Topics: 8
      Replies: 10
      Points: 0
      Rank: Member

      Christian Sandfeld, I like where you were going with your solution, but sadly I can’t use the in operator with Powershell 1.0. Is there an “old” way to achieve this?

    • #31423
      Participant
      Topics: 3
      Replies: 62
      Points: 0
      Rank: Member

      That is a tough one. I don’t think I have ever written any scripts for version 1. That is like 10 years old or something. That would put you on Windows Server 2008 or Windows Server 2003?

      Please do a get-host or $host or $PSVersionTable in a console window and paste the result here.

      If you are on version one, I highly recommend an upgrade.

Viewing 5 reply threads
  • The topic ‘Probably Easy’ is closed to new replies.