Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The PowerShell -and conditional operator

Tags:

powershell

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!

like image 290
basickarl Avatar asked Mar 26 '12 12:03

basickarl


2 Answers

You can simplify it to

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

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

like image 97
Joey Avatar answered Nov 16 '22 15:11

Joey


Another option:

if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
   ...
}
like image 10
Shay Levy Avatar answered Nov 16 '22 17:11

Shay Levy