Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $true and $false under the hood

So I was playing around with PowerShell a little and came across a somewhat surprising result in the following code

function returns_true(){
    return $true
}

function returns_false(){
    return $false
}

if (returns_true -eq $true){
    Write-Host "I return true"
}

if (returns_false -eq $false){
    Write-Host "I return false"
}
$myval = returns_false
Write-Host $myval

Running this gives me the following output

I return true
False

I was expecting this to return either

I return true
I return false
False

or just

False

Could someone explain what is going on here. What is PowerAhell doing under the hood that allows me to evaluate -eq $true, but not -eq $false when I return $true and $false?

like image 293
Matt Avatar asked Mar 05 '18 16:03

Matt


2 Answers

What's actually happening here is that the parser is seeing -eq $true and -eq $false as arguments being passed to the functions.

To see that this is the case, add [CmdletBinding()]Param() to the functions like this:

function returns_true(){
[CmdletBinding()]
Param()
    return $true
}
like image 154
Mike Shepard Avatar answered Sep 19 '22 13:09

Mike Shepard


Better explanation as to what's happening: https://stackoverflow.com/a/49115149/9446818

Parentheses help. What you really want is:

if ((returns_true) -eq $true){

and

if ((returns_false) -eq $false){
like image 37
Brandon Avatar answered Sep 22 '22 13:09

Brandon