Why is $false -eq “” true?

后端 未结 2 787
逝去的感伤
逝去的感伤 2020-12-03 17:44

The following code segments output true:

$x = ($false -eq \"\") 
Write-Host $x

$x = ($false -eq 0) 
Write-Host $x

Since $false and \"\" ar

2条回答
  •  不思量自难忘°
    2020-12-03 18:45

    Just sharing one experience here which might be worth noting when we convert a string value to boolean:

    What I was doing is reading a boolean string value from a configuration file which was getting stored in a variable as shown below:

    $valueReadFromFile = "false"
    

    Now, I wanted to convert it to Boolean value. Since I was not aware of Convert class in PowerShell I used casting instead as shown below in a bool condition of if block:

    if([bool]$valueReadFromFile -eq $true)
    {
        echo "This message shouldn't get printed in current scenario"
    }
    

    But I was on a wrong turn. Everytime below message was getting printed because non-empty string in PowerShell gets casted to literal boolean value $true:

    This message shouldn't get printed in current scenario

    When my program started to behave incorrectly then I explored more and came to know about convert class. I fixed my code as below:

    $actualBoolValue = [System.Convert]::ToBoolean($valueReadFromFile.Trim())
    

提交回复
热议问题