1

I have following powershell script

function Func1{
    return $true
}

function Func2{
    return $false
}

if (Func1 -eq $true){
    Write-Host "Func1 is true"
}
else{
    Write-Host "Func1 is false"
}

if (Func2 -eq $true){
    Write-Host "Func2 is true"
}
else{
    Write-Host "Func2 is false"
}

if (Func1 -eq $true -and Func2 -eq $true){
    Write-Host "Func1 is true and Func2 is true"
}

I am getting following output from this program

Func1 is true
Func2 is false
Func1 is true and Func2 is true

I am not expecting the third line in the output. What is wrong here?

Shino C G
  • 1,237
  • 11
  • 17
  • PowerShell has always been a pain in regards of return types and values... I don't know why exactly it does that, but if you write `if ( [bool](Func1) -eq $true -and ...` it works. Sorry that I can't give an answer as to why PowerShell does that. I had a lot of trouble with return types in the past which is why I always cast the type and define all variable with a type like this `[string]$myVar = "test"` or `[bool]$retVal = $false` –  Feb 01 '23 at 07:30
  • There has to be a distinction between *parameters* and *operators*. When you use: `fuc1 -eq $true` inside your `if` condition, how would it be able to tell if `-eq` is a *parameter* or an *operator* to the conditional statement? You have to tell PowerShell to evaluate it first, which you can do so by wrapping it inside a *grouping operator* `(...)`. So, it should be `if ((func1) -eq $true) { ... }`, or preferably swapping the operands. – Abraham Zinala Feb 01 '23 at 07:42
  • 1
    That is because you are in [argument mode](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_parsing#argument-mode). To change it to an [expression](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_parsing#expression-mode), you might use parenthesis: `(Func1) -eq $true -and (Func2) -eq $true` – iRon Feb 01 '23 at 08:01

0 Answers0