繁体   English   中英

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

[英]Switch parameters and powershell.exe -File parameter

微软称:

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

我有一个简单的脚本:

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

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

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

结果我收到一个错误: 在此输入图像描述

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

如果我删除[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

在此输入图像描述

它也是Microsoft Connect上的活动错误

有一些方法可以使这项工作,例如扩展字符串

[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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM