切换参数和powershell.exe -File参数

时间:2015-05-29 07:44:35

标签: powershell

根据微软的说法:

  

在极少数情况下,您可能需要为switch参数提供布尔值。要在File参数的值中为switch参数提供布尔值,请将参数名称和值括在花括号中,例如:-File。\ Get-Script.ps1 {-All:$ False}

我有一个简单的脚本:

[CmdletBinding()] 
Param
(
    [switch] $testSwitch
)
$testSwitch.ToBool()

接下来我试图以这种方式运行它:

powershell -file .\1.ps1 {-testSwitch:$false}

结果我收到一个错误: enter image description here

但如果相信微软它应该有用。

如果我删除了[CmdletBinding]属性,则不会发生此错误,但由于某些原因,$testSwitch.ToBool()会返回False,无论我是否通过$True$False

为什么呢?这种行为的原因是什么?

2 个答案:

答案 0 :(得分:8)

解决方法是不使用-File参数:

c:\scripts>powershell.exe .\test.ps1 -testswitch:$true
True
c:\scripts>powershell.exe .\test.ps1 -testswitch:$false
False

enter image description here

它也是Microsoft Connect

上的活跃错误

答案 1 :(得分:1)

有一些方法可以使这项工作,例如expanding the string

[CmdletBinding()]
Param(
  [Parameter()]$testSwitch
)

$ExecutionContext.InvokeCommand.ExpandString($testSwitch)

但是,你真的不需要这样做。只需在有或没有开关的情况下运行脚本,并检查是否存在switch参数:

[CmdletBinding()]
Param(
  [switch][bool]$testSwitch
)

$testSwitch.IsPresent

演示:

C:\>powershell -File .\test.ps1 -testSwitch
True

C:\>powershell -File .\test.ps1
False
相关问题