测试某些东西是否“假”

时间:2015-08-01 00:20:27

标签: powershell

在Python中,我可以说

test_variable = ""
if test_variable:
    print("I wont make it here because I'm False like")

test_variable = False
if test_variable:
    print("I wont make it here because I'm False like")

test_variable = None
if test_variable:
    print("I wont make it here because I'm False like")

总的来说,我可以说明if variable来判断某些事情是否“错误”。

在PowerShell中,我遇到了必须同时检查$Null和空字符串的情况。

If (($git_pull_output -eq $Null) -or ($git_pull_output -eq ""))

有没有一种方法可以检查某些东西是否“像假”?

2 个答案:

答案 0 :(得分:3)

$false是一个值为false的自动变量。请参阅Get-Help about_Automatic_Variables

然而:

  

在Powershell中,我遇到了必须同时检查$Null和空字符串的情况。

为此,您应该使用IsNullOrEmpty() static member function of the System.String class

if ([string]::IsNullOrEmpty($git_pull_output)) { [...] }

您也可以考虑使用IsNullOrWhiteSpace()静态方法。

答案 1 :(得分:3)

另一个简单的"虚假的" test只是将变量评估为布尔值

PS C:\Users\Matt> $test = ""
PS C:\Users\Matt> If($test){"'' Test is good"}

PS C:\Users\Matt> $test = $false
PS C:\Users\Matt> If($test){"False test is good"}

PS C:\Users\Matt> $test = " "
PS C:\Users\Matt> If($test){"Space test is good"}

Space test is good

请注意,唯一成功的测试是$test = " "

如果空白是一个问题,那么你也希望避免这个问题,那么IsNullOrWhiteSpace()就是你的方法

PS C:\Users\Matt> [string]::IsNullOrWhiteSpace(" ")
True
相关问题