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
?
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
}
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){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With