PowerShell – Multiple (-and) (-or) within a single If statement

I had a hard time finding examples on the web on how or if you could code multiple If’s into a single If statement, so I thought I would just quick post up an example once I figured out how to do it. Perhaps I wasn’t looking in the right places but all the examples I saw were just a single (-and) or (-or) in the code.

So based on being able to code an If statement in either of the following fashions:

If ($someAttribute -eq $false -or $someAttribute -eq $Null){

}

or the following:

If (($someAttribute -eq $false) -or ($someAttribute -eq $Null)){

}

Then we should be able to do a combined effort:

If (($someAttribute -eq $false -or $someAttribute -eq $Null) -and ($someUser -eq “UserID123”)){
       Write-Host “Switching to True”
       Set-QADUser $someUser -Service “MyDomain.org” -ObjectAttributes @{$someAttribute = $True}
       If (!$?) {Write-Host “Error: $($error[0])”}
}

So if $someAttribute is either $false or $Null AND #someUser equalsUserID123″ then do something… in this case I switch the Attribute someAttribute to $true and do some error checking.

~ITNotes

3 thoughts on “PowerShell – Multiple (-and) (-or) within a single If statement

  1. I noticed that this does NOT work as expected: “If (($someAttribute -ne $false -or $someAttribute -ne $Null) -and ($someUser -eq “UserID123″)){”

    Any idea how to efficiently exclude instead of include with nested If statements?

  2. If (!($Something -eq $true)) {Write-Host False}

    The exclamation point is the not or exclusion I think you are looking for.

  3. You will need to look into deMorgans laws
    !(a ^ b) = !a v !b
    !(a v b) = !a ^ !b

Leave a Reply

Your email address will not be published. Required fields are marked *