How to pass boolean values to a PowerShell script from a command prompt How to pass boolean values to a PowerShell script from a command prompt powershell powershell

How to pass boolean values to a PowerShell script from a command prompt


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)


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 $falseTurn: 1Unify: 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 -UnifyTurn: 1Unify: True


Try setting the type of your parameter to [bool]:

param(    [int]$Turn = 0    [bool]$Unity = $false)switch ($Unity){    $true { "That was true."; break }    default { "Whatever it was, it wasn't true."; break }}

This example defaults $Unity to $false if no input is provided.

Usage

.\RunScript.ps1 -Turn 1 -Unity $false