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-childitemWrite-Output $list}else {Write-Output "Enter file name..."read-host $fileWrite-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$false7
u/idontknowwhattouse33 Jan 09 '23
Might be better to use a
[switch]as that appears to be your usecase.https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.3
7
u/mooscimol Jan 09 '23
Non empty string 'false' has been converted to boolean value of true, which is to be expected. $false should be handled correctly, maybe you provided in quotes which again has been converted from string.
Nevertheless, as suggested I would use parameter of [switch] type which should be less error prone to incorrect input parameters.
3
u/PowerShell-Bot Jan 09 '23
It appears that you have used inline code formatting when a code block should have been used.
Consider using a code block for longer sequences of code. To correct the formatting, highlight your code then click the ‘Code Block’ button in the editing toolbar.
Beep-boop, I am a bot. | Remove-Item
2
u/chanataba Jan 09 '23
Is this what you're looking for?