The PowerShell -and conditional operator
PowershellPowershell Problem Overview
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!
Powershell Solutions
Solution 1 - Powershell
You can simplify it to
if ($user_sam -and $user_case) {
...
}
because empty strings coerce to $false
(and so does $null
, for that matter).
Solution 2 - Powershell
Another option:
if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
...
}
Solution 3 - Powershell
Try like this:
if($user_sam -ne $NULL -and $user_case -ne $NULL)
Empty variables are $null
and then different from "" ([string]::empty
).
Solution 4 - Powershell
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