63

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!

4 Answers 4

93

You can simplify it to

if ($user_sam -and $user_case) {
  ...
}

because empty strings coerce to $false (and so does $null, for that matter).

Sign up to request clarification or add additional context in comments.

Comments

10

Another option:

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

Comments

6

Try like this:

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

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

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.