How to pass boolean values to a PowerShell script from a command prompt
It appears that powershell.exe does not fully evaluate script arguments when the -File
parameter is used. In particular, the $false
argument is being treated as a string value, in a similar way to the example below:
PS> function f( [bool]$b ) { $b }; f -b '$false'
f : Cannot process argument transformation on parameter 'b'. Cannot convert value
"System.String" to type "System.Boolean", parameters of this type only accept
booleans or numbers, use $true, $false, 1 or 0 instead.
At line:1 char:36
+ function f( [bool]$b ) { $b }; f -b <<<< '$false'
+ CategoryInfo : InvalidData: (:) [f], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,f
Instead of using -File
you could try -Command
, which will evaluate the call as script:
CMD> powershell.exe -NoProfile -Command .\RunScript.ps1 -Turn 1 -Unify $false
Turn: 1
Unify: False
As David suggests, using a switch argument would also be more idiomatic, simplifying the call by removing the need to pass a boolean value explicitly:
CMD> powershell.exe -NoProfile -File .\RunScript.ps1 -Turn 1 -Unify
Turn: 1
Unify: True
A more clear usage might be to use switch parameters instead. Then, just the existence of the Unify parameter would mean it was set.
Like so:
param (
[int] $Turn,
[switch] $Unify
)