Powershell和条件运算符

Kar*_*son 57 powershell

要么我不理解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!"
}
Run Code Online (Sandbox Code Playgroud)

我希望你理解我试图输出的内容.我想填充$ user_sam和$ user_case以访问第一个语句!

Joe*_*oey 88

你可以简化它

if ($user_sam -and $user_case) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

因为空字符串强制执行$false($null对于那个问题也是如此).


Sha*_*evy 9

另外一个选项:

if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
   ...
}
Run Code Online (Sandbox Code Playgroud)


CB.*_*CB. 5

尝试这样:

if($user_sam -ne $NULL -and $user_case -ne $NULL)
Run Code Online (Sandbox Code Playgroud)

空变量则$null与“”([string]::empty)不同。


EBG*_*een 5

您显示的代码执行您想要的操作,如果这些属性在未填充时等于“”。例如,如果它们在未填充时等于 $null,则它们将不等于“”。这是一个例子来证明你所拥有的东西对“”有用:

$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False
Run Code Online (Sandbox Code Playgroud)