none
Powershell - If statements ( -notin & -or ) RRS feed

  • Question

  • Hi,

    First off please understand I'm not a script person, but trying my best to understand enough to perform some basic tasks :)

    Basically what I'm trying to do is use an If statement to read through multiple arrays and 'do stuff' if a match is found, but also to notify if its not found. I was trying to use the below code;

    ### Regex to remove non "0-9" or "." characters
    $pattern = '[^0-9.]'
    
    ### Get Gateway IP
    $GW = Ipconfig | Select-String Gateway | Select -First 1
    $GW2 = $GW -replace $pattern, ' '
    $GWFinal = $GW2.Trim(" ",".")
    
    ### define site gateways in arrays
    $Site1 = "192.168.1.254","192.168.1.254","192.168.3.254"
    $Site2 = "192.168.2.254","192.168.2.254","192.168.4.254"
    $Site3 = "192.168.101.254","192.168.102.254","192.168.100.254"
    
    
    If ($GWFinal -notin $Site1 -or $Site2 -or $Site3)
        {
         Write-Host "Its not in any!"
        }
    
    Else {
          Write-Host "Gateway Found!"
         }
    
         If ($GWFinal -in $Site1) {
                                   "Do Stuff1"
                                  }
         Else {}
    
              If ($GWFinal -in $Site2) {
                                        "Do Stuff2"
                                       }
              Else {}
    
                   If ($GWFinal -in $Site3) {
                                             "Do Stuff3"
                                            }
                   Else {}

    The Result returned are as follows;

    Its not in any!
    Do Stuff3

    So its clearly picking up my gateway as being in $Site3, but my use of the -or statements mustn't be good in the first 'If' block.

    If I amend the first If block to only have one array specified the -notin works perfectly, so therefore I assume I can't use multiple '-values' or I've not formatted it correctly.

    Would some nice person out there kindly point out what I'm doing wrong, or suggest an alternative approach?

    Thanks in advance

    Adam

    Thursday, April 27, 2017 10:58 AM

Answers

  • Syntax!  Logic!

    If ($GWFinal -notin $Site1 -and $GWFinal  -notin $Site2 -and $GWFinal -notin $Site3)


    \_(ツ)_/




    • Edited by jrv Thursday, April 27, 2017 11:24 AM
    • Marked as answer by Adam_231 Thursday, April 27, 2017 12:37 PM
    Thursday, April 27, 2017 11:23 AM

All replies