微软称:
在极少数情况下,您可能需要为switch参数提供布尔值.要在File参数的值中为switch参数提供布尔值,请将参数名称和值括在花括号中,如下所示:-File.\ Get-Script.ps1 {-All:$ False}
我有一个简单的脚本:
[CmdletBinding()]
Param
(
[switch] $testSwitch
)
$testSwitch.ToBool()
Run Code Online (Sandbox Code Playgroud)
接下来我试图以这种方式运行它:
powershell -file .\1.ps1 {-testSwitch:$false}
Run Code Online (Sandbox Code Playgroud)
结果我收到一个错误:

但如果相信微软它应该工作.
如果我删除[CmdletBinding]属性,则不会发生此错误,但由于某些原因$testSwitch.ToBool()返回False,尽管我是否通过$True或$False.
为什么?这种行为的原因是什么?
解决方法是不使用-File参数:
c:\scripts>powershell.exe .\test.ps1 -testswitch:$true
True
c:\scripts>powershell.exe .\test.ps1 -testswitch:$false
False
Run Code Online (Sandbox Code Playgroud)

它也是Microsoft Connect上的活动错误