[powershell] The PowerShell -and conditional operator

Either I do not understand the documentation on MSDN or the documentation is incorrect.

if($user_sam -ne "" -and $user_case -ne "")
{
    Write-Host "Waaay! Both vars have values!"
}
else
{
    Write-Host "One or both of the vars are empty!"
}

I hope you understand what I am attempting to output. I want to populate $user_sam and $user_case in order to access the first statement!

This question is related to powershell

The answer is


The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":

$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False

Try like this:

if($user_sam -ne $NULL -and $user_case -ne $NULL)

Empty variables are $null and then different from "" ([string]::empty).


Another option:

if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
   ...
}