According Microsoft:
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 have a simple script:
[CmdletBinding()]
Param
(
[switch] $testSwitch
)
$testSwitch.ToBool()
Next I am trying to run it this way:
powershell -file .\1.ps1 {-testSwitch:$false}
As result I receive an error:
But if believe Microsoft it should work.
If I delete [CmdletBinding]
attribute this error will not occur, but for some reasons $testSwitch.ToBool()
returns False despite whether I pass $True
or $False
.
Why? What are the reasons of this behaviour?
The workaround is to not use the -File parameter:
c:\scripts>powershell.exe .\test.ps1 -testswitch:$true
True
c:\scripts>powershell.exe .\test.ps1 -testswitch:$false
False
It is also an active bug on Microsoft Connect
There are ways to make this work, for instance expanding the string :
[CmdletBinding()]
Param(
[Parameter()]$testSwitch
)
$ExecutionContext.InvokeCommand.ExpandString($testSwitch)
However, you don't really need to do that. Simply run the script with or without the switch and check for the presence of the switch parameter:
[CmdletBinding()]
Param(
[switch][bool]$testSwitch
)
$testSwitch.IsPresent
Demonstration:
C:\>
True
C:\>
False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.