I have to invoke a PowerShell script from a batch file. One of the arguments to the script is a boolean value:
C:\\Windows\\System32\\WindowsPowerShell\\v1.0
Running powershell scripts on linux from bash gives the same problem. Solved it almost the same as LarsWA's answer:
Working:
pwsh -f ./test.ps1 -bool:true
Not working:
pwsh -f ./test.ps1 -bool=1
pwsh -f ./test.ps1 -bool=true
pwsh -f ./test.ps1 -bool true
pwsh -f ./test.ps1 {-bool=true}
pwsh -f ./test.ps1 -bool=$true
pwsh -f ./test.ps1 -bool=\$true
pwsh -f ./test.ps1 -bool 1
pwsh -f ./test.ps1 -bool:1
This is an older question, but there is actually an answer to this in the PowerShell documentation. I had the same problem, and for once RTFM actually solved it. Almost.
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe
Documentation for the -File parameter states that "In rare cases, you might need to provide a Boolean value for a switch parameter. To provide a Boolean value for a switch parameter in the value of the File parameter, enclose the parameter name and value in curly braces, such as the following: -File .\Get-Script.ps1 {-All:$False}"
I had to write it like this:
PowerShell.Exe -File MyFile.ps1 {-SomeBoolParameter:False}
So no '$' before the true/false statement, and that worked for me, on PowerShell 4.0
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 $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