当前位置: 动力学知识库 > 问答 > 编程问答 >

powershell - Test if something is "False Like"

问题描述:

In Python I can say

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")

And in general I can just get away with stating if variable to test if something is "False Like."

In PowerShell I've run into the case where I have to check both for $Null and empty string.

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

Is there a PowerShell is there a way to check if something is "False like"?

网友答案:

Another simple "false like" test is to just evaluate the variable as a boolean

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

Note the only test that succeeded was the when $test = " "

If whitespace was an issue you were looking to avoid as well then IsNullOrWhiteSpace() is the method for you

PS C:\Users\Matt> [string]::IsNullOrWhiteSpace(" ")
True
网友答案:

$false is an automatic variable with the value of false. See Get-Help about_Automatic_Variables.

However:

In Powershell I've run into the case where I have to check both for $Null and empty string.

For this you should use the IsNullOrEmpty() static member function of the System.String class:

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

You may also consider the IsNullOrWhiteSpace() static method.

分享给朋友:
您可能感兴趣的文章:
随机阅读: