In Windows PowerShell, there is no way to pass Boolean values when powershell.exe https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe's
-File
parameter is used - this has has since been corrected in PowerShell (Core) 7+ https://github.com/PowerShell/PowerShell/blob/master/README.md, whose CLI is pwsh.exe https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pwsh[1].
Use the 解决方法 that JosefZ https://stackoverflow.com/users/3439404/josefz推荐:
Use of -Command
(-c
)代替-File
使 PowerShell 将参数视为PowerShell 源代码而不是字面上的论证, 在这种情况下$false
被正确识别(为简洁起见,省略了其他 CLI 参数)。
powershell -c "& \"%~dp0\foo.ps1\" -Name 'abc' -MySwitch:$false"
Note:
-
&
, the 呼叫接线员 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#call-operator-,必须用来调用脚本文件,因为它的路径是quoted.
-
PowerShell 需要嵌入"
字符。在命令行上转义为\"
(不作为`"
or ""
,它的工作方式inside电源外壳)。
- With
-Command
,如果您需要逐字嵌入"
在嵌入的内部\"...\"
string, use `\"
(sic).
- 虽然您可以将脚本路径括起来
'...'
相反,为了避免转义的需要,如果扩展的目录文件路径(%dp0
) 恰好包含'
字符。本身。
-
有关何时使用的一般指导-File
vs. -Command
以及适用的不同语法规则,请参阅这个答案 https://stackoverflow.com/a/57443822/45375.
在概念上:
-
您的代码已经使用了在 PowerShell 中传递布尔参数的首选方法:[switch] https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Functions#switch-parameters参数(有时称为flags).
-
开关参数imply布尔值:如果指定了给定开关(仅按名称)(-MySwitch
), $true
是暗示的;如果是完全缺席, $false
是暗示的。那是,simply omitting -MySwitch:$false
也会解决你的问题.
- 相比之下,
[bool]
- 类型参数 - 总是require争论——应该避免。这个帖子 https://stackoverflow.com/q/49130184/45375对比[bool]
with [switch]
参数。
-
当(PowerShell-内部)你(总是)can通过explicit value(正如你尝试的那样
-MySwitch:$false
,注意必需的:
分隔器, a space不会工作) - 这样做是only required在以下场景中:
[1] PowerShell (Core) 7+ supports the following Boolean values when -File
is used: $true
, $false
, true
, false
(and also $null
, but its interpretation differs: scripts (including with -File
) and functions interpret it as $false
, whereas cmdlets interpret it as $true
(!)).
Note that with -Command
- and therefore in all PowerShell code - true
and false
do not work, but 0
and 1
do.
Unfortunately, if you pass an unsupported value, you get the same error message in all scenarios, which in the -File
scenario misleadingly suggests that 0
and 1
work too.