PowerShell中的-And条件运算符

63
我对MSDN的文档要么理解不够,要么文档本身有误。
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!"
}

我希望你能理解我想输出什么。我想填充$user_sam和$user_case以便访问第一条语句!

4个回答

93
你可以简化为
if ($user_sam -and $user_case) {
  ...
}
因为空字符串会被强制转换为$false(同理,$null也是如此)。

10

另一个选项:

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

6
尝试以下方法:
if($user_sam -ne $NULL -and $user_case -ne $NULL)

空变量是$null,与""([string]::empty)不同。


5

您展示的代码只有当这些属性没有填写时才会执行您想要的功能。如果它们在未填写时等于$null,那么它们将不等于""。以下是一个例子,以证明您的代码将适用于"":

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接