Arbelac
Arbelac

Reputation: 1904

Checking if two variables either both not null or both null

I have been developing a script to send mail based on variables. I have a script like below.

Each of these 2 variables may be $null or not $null. What's the best practice to check for such condition?

Here is my script:

$variableA = ""
$variableB = ""

if($variableA) {
  Write-Host "mail send variableA"
} else {
  Write-Host "mail not send variableA"
}

if($variableB) {
  Write-Host "mail  send variableB"
} else {
  Write-Host "mail not send variableB"
}

Upvotes: 0

Views: 1292

Answers (1)

Robert Dyjas
Robert Dyjas

Reputation: 5217

You can use negated -xor operator:

# Either both nulls or both have values
(-not (($null -eq $a) -xor ($null -eq $b)))

One can disagree what's more readable. I'd personally just go with more explicit formula:

(($null -eq $a) -and ($null -eq $b)) -or 
(($null -ne $a) -and ($null -ne $b)) 

Remember to put $null in the left side of the comparison, it's considered as a best practice.

Upvotes: 1

Related Questions