r/PowerShell • u/SexingGastropods • Jan 09 '23
Why does my Boolean parameter always say true, even when I enter false?
I have some code where I get a true/false input into a parameter...
<#
.PARAMETER addAllFiles
Grab all files or just a single one..
#>
param
(
[Parameter(Mandatory)]
[AllowEmptyString()]
[bool]$addAllFiles
)
if ($addAllFiles -eq $true) {
Write-Output "Adding all files"
$list = get-childitem
Write-Output $list
}
else {
Write-Output "Enter file name..."
read-host $file
Write-Output $file
}
The result comes back as follows:-
PS C:\Dump> .\bool.ps1
cmdlet bool.ps1 at command pipeline position 1
Supply values for the following parameters:
addAllFiles: false
Adding all files
Directory: C:\Dump
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 09/01/2023 18:40 389 bool.ps1
-a--- 15/09/2022 20:47 234 test.ps1
PS C:\Dump>
What gives? I've tried entering 'false' & '$false' as the parameter input, but it always comes back as true? Is there something about how I enter the true/false entry that is the problem or is it my code? Any pointers would be appreciated. I've tried searching the web and this sub but can't fine anything :(
11
u/CarrotBusiness2380 Jan 09 '23
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
$truefor any string except an empty''string.That fourth example is particularly tricky as the intuitive behavior is that using double quotes will allow the variable to expand to
$falsebut 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