【问题标题】:Switch parameters and powershell.exe -File parameter切换参数和powershell.exe -File参数
【发布时间】:2015-05-29 07:44:35
【问题描述】:

根据微软:

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

我有一个简单的脚本:

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

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

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

结果我收到一个错误:

但如果相信微软它应该可以工作。

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

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

【问题讨论】:

  • 这也适用于普通布尔值。

标签: powershell


【解决方案1】:

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

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

这也是Microsoft Connect上的一个活跃错误

【讨论】:

    【解决方案2】:

    有办法让这个工作,例如expanding the string

    [CmdletBinding()]
    Param(
      [Parameter()]$testSwitch
    )
    
    $ExecutionContext.InvokeCommand.ExpandString($testSwitch)
    

    但是,您实际上并不需要这样做。只需在带或不带开关的情况下运行脚本并检查开关参数是否存在:

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

    演示:

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

    【讨论】:

    • 我确实需要指定 $true 或 $false。这是有原因的。
    • 这个命令实际上做了什么 - $ExecutionContext.InvokeCommand.ExpandString($testSwitch)?
    • @olegk 基本上,它在字符串中扩展(PowerShell)表达式和变量。
    猜你喜欢
    • 1970-01-01
    • 2013-06-14
    • 2017-06-12
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2021-11-06
    相关资源
    最近更新 更多