pooja520  PowerShell is not strongly-typed language like C#, where the compiler wouldn't even let you run a test like [bool] -eq [string]. Where PowerShell does allow such operations, they come with behaviours you need to know about. What your first test ($Stat -eq 'fal') is testing is for the existence (i.e. present and not null) of the right of the operator - since the types themselves don't match - and comparing that to the value on the left. So, rather than: $Stat -eq 'fal'; You're actually comparing (since 'fal' both exists and is not null): $Stat -eq $true; Hence the result is $true. Here's my own example illustrating this very point using an even more complex type on the right-hand side:  Now, if you swap the values around, you'd expect to get the same outcome, but you don't. This is because PowerShell is now testing for equality against the complex ActiveDirectorySite class, which the Boolean isn't going to match (since the test is something called a reference equality test - but this isn't important.) So, this brings me to the crux of your issue: how can you reliably test a Boolean against another Boolean? (as distinct from your example that is a Boolean against a String.) I'd posit two basic ways though there are more: Swap the Boolean to be on the right side of the operator, with the object you're comparing to the left;Use the .NET .Equals() method on the Boolean object to assess the object being checked.  PowerShell's implicit existence testing can be quite a handy feature, but in the case of working with the Boolean type also requires a bit more care - and testing - to avoid unintended outcomes. Cheers,Lain Answer from lainrobertson on techcommunity.microsoft.com
Top answer
1 of 1
2
pooja520  PowerShell is not strongly-typed language like C#, where the compiler wouldn't even let you run a test like [bool] -eq [string]. Where PowerShell does allow such operations, they come with behaviours you need to know about. What your first test ($Stat -eq 'fal') is testing is for the existence (i.e. present and not null) of the right of the operator - since the types themselves don't match - and comparing that to the value on the left. So, rather than: $Stat -eq 'fal'; You're actually comparing (since 'fal' both exists and is not null): $Stat -eq $true; Hence the result is $true. Here's my own example illustrating this very point using an even more complex type on the right-hand side:  Now, if you swap the values around, you'd expect to get the same outcome, but you don't. This is because PowerShell is now testing for equality against the complex ActiveDirectorySite class, which the Boolean isn't going to match (since the test is something called a reference equality test - but this isn't important.) So, this brings me to the crux of your issue: how can you reliably test a Boolean against another Boolean? (as distinct from your example that is a Boolean against a String.) I'd posit two basic ways though there are more: Swap the Boolean to be on the right side of the operator, with the object you're comparing to the left;Use the .NET .Equals() method on the Boolean object to assess the object being checked.  PowerShell's implicit existence testing can be quite a handy feature, but in the case of working with the Boolean type also requires a bit more care - and testing - to avoid unintended outcomes. Cheers,Lain
Discussions

Strange way to write an if-check on a boolean
This is a code smell. The value of $JobFlag can only ever be scalar (it's either declared with a boolean value or assigned a value by Invoke-DSCJob which only returns a scalar). It's possible this is leftover from a previous version of the code where $JobFlag was a collection. Assuming this is the case, the intention of the code is to perform an equality comparison against the last element in the collection (which can be achieved with $JobFlag[-1]). if ($JobFlag -eq $True) is in itself a code smell and can be reduced to if ($JobFlag). More on reddit.com
🌐 r/PowerShell
13
8
September 18, 2023
powershell - True/false test returning unexpected results - Stack Overflow
Good question, using "$Path" was ... or something different. 2021-03-25T15:48:36.883Z+00:00 ... In a comparison operation PowerShell automatically converts the second operand to the type of the first operand. Since you're comparing a boolean value to a string, the string will be cast to a boolean value. Empty strings will be cast to $false and non-empty strings will be cast to $true... More on stackoverflow.com
🌐 stackoverflow.com
Boolean set to both $true AND $false simultaneously breaking if statement

It looks like you've accidentally created an array of boolean values instead of a single one. So your Write-Verbose statement is expanding the array into a space delimited list.

More on reddit.com
🌐 r/PowerShell
17
5
June 25, 2020
Why does my Boolean parameter always say true, even when I enter false?
You should use a switch as recommended by \u\idontknowwhattouse33 but it is important to understand what caused the problem. The problem though is that when powershell casts a string to a boolean it will cast to $true for any string except an empty '' string. PS C:\> [bool]'false' True PS C:\> [bool]'$false' True PS C:\> [bool]'' False PS C:\> [bool]"$false" True PS C:\> [bool]$false False That fourth example is particularly tricky as the intuitive behavior is that using double quotes will allow the variable to expand to $false but it is still cast to a non-empty string before it is cast to a boolean. The answer then is not to use quotes at all and to pass the automatic variable $false .\bool.ps1 -addAllFiles $false More on reddit.com
🌐 r/PowerShell
13
5
January 9, 2023
🌐
PowerShell Forums
forums.powershell.org › powershell help
$true or $false in powershell function - PowerShell Help - PowerShell Forums
December 14, 2020 - To my understanding, result should be always $false as it has return $false at the bottom of the script or I’m missing something? Can someone explains the logic here. Thank you #This function checks to see if the file should be ignored.
🌐
PDQ
pdq.com › blog › how-to-use-if-statements-in-powershell
How to use if statements in PowerShell | PDQ
A PowerShell if statement evaluates a condition and runs a code block when that condition is true. PowerShell checks the expression in parentheses, and if it returns true, it executes the statements inside the braces.
🌐
Xah Lee
xahlee.info › powershell › powershell_boolean.html
PowerShell: True, False (boolean)
May 26, 2021 - Hashtable (empty or not) $false · $null · Zero · Empty String · Empty Array · $x = 3 [bool] $x # True $x = "" [bool] $x # False · PowerShell: True, False (boolean) PowerShell: Boolean Operators · PowerShell: If Then Else (Flow Control) PowerShell: Test Equality ·
🌐
Reddit
reddit.com › r/powershell › strange way to write an if-check on a boolean
r/PowerShell on Reddit: Strange way to write an if-check on a boolean
September 18, 2023 -

Source: https://github.com/Esri/arcgis-powershell-dsc/blob/main/Modules/ArcGIS/ArcGIS.psm1

Lines 1953 and 1973 specifically.

I am looking at some powershell code (link above), and don't understand why a simple boolean check is written as:

$JobFlag = $True
# more code here...
if ($JobFlag[$JobFlag.Count - 1] -eq $True) { # CODE HERE }

There are some functions that might be called before the if-statement, but as far as I can tell, they return either $True or $False

Is there any reason for not writing a plain:

if ($JobFlag -eq $True)

I am by now means an experienced powershell user, therefore curious.

Top answer
1 of 4
17

The error comes from the fact that the return value of Test-Path is a Boolean type.

Hence, don't compare it to strings representation of Boolean but rather to the actual $false/$true values. Like so,

$Path = Test-Path  c:\temp\First

if ($Path -eq $false)
{
    Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq $true)
{
    Write-Host " what the smokes"
}

Also, note that here you could use an else statement here.

Alternatively, you could use the syntax proposed in @user9569124 answer,

$Path = Test-Path  c:\temp\First

if (!$Path)
{
    Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path)
{
    Write-Host " what the smokes"
}
2 of 4
5

In a comparison operation PowerShell automatically converts the second operand to the type of the first operand. Since you're comparing a boolean value to a string, the string will be cast to a boolean value. Empty strings will be cast to $false and non-empty strings will be cast to $true. Jeffrey Snover wrote an article "Boolean Values and Operators" about these automatic conversions that you can check for further details.

As a result this behavior has the (seemingly paradox) effect that each of your comparisons will evaluate to the value of your variable:

PS C:\> $false -eq 'False'
False
PS C:\> $false -eq 'True'
False
PS C:\> $true -eq 'False'
True
PS C:\> $true -eq 'True'
True

Essentially that means that if your Test-Path statements evaluates to $false neither of your conditions will match.

As others have pointed out you can fix the issue by comparing your variable to actual boolean values, or by just using the variable by itself (since it already contains a boolean value that can be evaluated directly). However, you need to be careful with the latter approach. In this case it won't make a difference, but in other situations automatic conversion of different values to the same boolean value might not be the desired behavior. For instance, $null, 0, empty string and empty array are all interpreted as a boolean value $false, but can have quite different semantics depending on the logic in your code.

Also, there is no need to store the result of Test-Path in a variable first. You can put the expression directly into the condition. And since there are only two possible values (a file/folder either exists or doesn't exist), there is no need to compare twice, so your code could be reduced to something like this:

if (Test-Path 'C:\temp\First') {
    Write-Host 'what the smokes'
} else {
    Write-Host 'notthere' -ForegroundColor Yellow
}
Find elsewhere
🌐
LazyAdmin
lazyadmin.nl › home › how to use powershell if else statements
How to use PowerShell If Else Statements — LazyAdmin
May 9, 2023 - $role = "developer" if (($role -eq 'admin') -or ($role -eq 'developer')) { # code to execute write-host 'The user is allowed to continue' } The PowerShell If statement checks if a particular condition is true, but sometimes you only want to ...
🌐
EDUCBA
educba.com › home › data science › data science tutorials › powershell tutorial › powershell boolean
PowerShell Boolean | How Boolean type works in PowerShell?
March 4, 2023 - PowerShell Boolean operators are $true and $false which mentions if any condition, action or expression output is true or false and that time $true and $false output returns as respectively, and sometimes Boolean operators are also treated as ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_if
about_If - PowerShell | Microsoft Learn
January 16, 2025 - If <test1> is true, <statement list 1> runs, and PowerShell exits the if statement. If <test1> is false, PowerShell evaluates the condition specified by the <test2> conditional statement.
🌐
TutorialsPoint
tutorialspoint.com › powershell › if_else_statement_in_powershell.htm
Powershell - If Else Statement
Following is the syntax of an if...else statement − · if(Boolean_expression) { // Executes when the Boolean expression is true }else { // Executes when the Boolean expression is false }
🌐
Reddit
reddit.com › r/powershell › boolean set to both $true and $false simultaneously breaking if statement
r/PowerShell on Reddit: Boolean set to both $true AND $false simultaneously breaking if statement
June 25, 2020 -

UPDATE: This is resolved.

I'm having trouble where an if statement looking at the value of a boolean variable that I'm setting via the return from a custom function is evaluating to true and executing because the boolean value is both $true and $false at the same time somehow.

Consider the following pseudo-code that is a highly simplified example of what I'm trying to do:

function Invoke-Example {
	$Execute = $null
	$Something = $false
	$SomethingElse = $false
	
	if ($Something) {
		$Execute = $true
	}
	if ($SomethingElse) {
		$Execute = $true
	}	
	
	Write-Verbose -Message "Value of `$Execute: $Execute" -Verbose
	
	if ($Execute) {
		Return $true
	}
	else {
		Return $false
	}
}

$Execute = $null
$Execute = Invoke-Example
Write-Verbose -Message "Value of `$Execute: $Execute" -Verbose

if ($Execute) {
	Write-Verbose -Message "Executing..." -Verbose
}
else {
	Write-Verbose -Message "Not executing..." -Verbose
}

When running my actual code, I'm getting something akin to this (output from my pseudo-code):

VERBOSE: Value of $Execute:

VERBOSE: Value of $Execute: True False

VERBOSE: Executing...

I'm expecting to see:

VERBOSE: Value of $Execute:

VERBOSE: Value of $Execute: False

VERBOSE: Not executing...

NOTE: When I execute the actual code in my example, it works as I would expect. I am not sure what is different, but of course my real code is far more complex.

Any idea what's going on? How can a boolean variable be both $true and $false simultaneously?

I'm using PowerShell 7.0 on Windows 10.

Edit: An issue appears to be that $Execute.Count is 2.

Edit 2: SOLVED! The issue was that in my function (Invoke-Example in my example), I was doing a -match operation and then using the $matches variable to set other variables based on the regex groupings, but I forgot that the -match statement by itself will return $true or $false. So this statement in combination with my Return statement was returning two boolean values even though I wasn't seeing "True" or "False" showing in the output when running the script.

Ending my -match statement with | Out-Null solved the issue. I show an updated version of my pseudo-code with the problematic match statement for illustrative purposes in a comment below.

Damn you, PowerShell, for your weird function return behavior!!!

🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › scripting › learn › deep-dives › everything-about-if
Everything you wanted to know about the if statement - PowerShell | Microsoft Learn
We can use normal PowerShell inside the condition statement. ... Test-Path returns $true or $false when it executes. This also applies to commands that return other values. ... It evaluates to $true if there's a returned process and $false if ...
🌐
Powershellexplained
powershellexplained.com › 2019-08-11-Powershell-if-then-else-equals-operator
Powershell: Everything you wanted to know about the IF statement
August 11, 2019 - If the value was $false, then it would skip over that scriptblock. In the previous example, the if statement was just evaluating the $condition variable. It was $true and would have executed the Write-Output command inside the scriptblock. In some languages, you can place a single line of code after the if statement and it will get executed. That is not the case in PowerShell.
🌐
Petri
petri.com › home › boolean values in powershell
Boolean Values in PowerShell
September 4, 2024 - If there is something in $p, the If expression will result in True. In a moment I’ll show you how we can turn this around. I also have corollary in that if you are evaluating a Boolean property, then you do not need to compare it to True or False.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › dsc › reference › schemas › config › functions › if
if - PowerShell | Microsoft Learn
July 4, 2025 - Returns a value based on whether a condition is true or false. ... The if() function returns a value based on whether a condition is true or false.
🌐
Adam the Automator
adamtheautomator.com › powershell-if-else
Back to Basics: Conditional Logic with PowerShell If Statement
If the result of Test 1 returns true, the code inside the If statement list will run, then PowerShell exits the If statement. If the result of Test 1 returns false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement.
Published   May 25, 2023
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › booleans in powershell: a comprehensive guide
Booleans in PowerShell: A Comprehensive Guide - SharePoint Diary
September 23, 2025 - Stick with $true and $false to keep things straightforward and avoid confusion. In PowerShell, booleans are used primarily in conditional statements, loops, and logical operations.
🌐
O'Reilly
oreilly.com › library › view › windows-powershell-quick › 0596528132 › ch01s06.html
Booleans - Windows PowerShell Quick Reference [Book]
September 27, 2006 - Boolean (true or false) variables are most commonly initialized to their literal values of $true and $false. When it evaluates them as part of a Boolean expression (i.e., an “if” statement,) though, PowerShell maps results into a suitable Boolean representation.
Author   Lee Holmes
Published   2006
Pages   115
🌐
AttuneOps
attuneops.io › powershell-if-else-and-elseif
Introduction to PowerShell If, Else, and ElseIf Statements - AttuneOps
September 30, 2025 - Yes, with PowerShell 7 and later, you can use a ternary operator. The syntax is: $result = $condition ? ‘TrueValue’: ‘FalseValue’ · This is an efficient way for simple conditional assigning. Yes, you can use the exit keyword to terminate a script instantly in this case. This might happen if a prerequisite check failed or something along those lines.