为什么我需要在PowerShell开关中使用'parametersetname'?

Tin*_*oon 1 powershell

我的问题是参数字段'parametersetname',它需要包含神秘的内容.

我有这个名为test.ps1的PowerShell(v3)脚本:

param([parameter(parametersetname="anything")][switch]$foo=$false)
$foo.IsPresent
Run Code Online (Sandbox Code Playgroud)

如果我在PowerShell IDE cmd行中运行它,如下所示:

.\test.ps1
Run Code Online (Sandbox Code Playgroud)

我明白了

> False
Run Code Online (Sandbox Code Playgroud)

用它来称呼它

.\test.ps1 -foo
Run Code Online (Sandbox Code Playgroud)

我明白了

> True
Run Code Online (Sandbox Code Playgroud)

两者都很好.然而,我花了一些时间(年龄)才意识到,为了切换到工作,我必须添加这个描述符"parametersetname".

因为如果我重复我的测试,但省略"parametersetname",如下所示:

param([parameter][switch]$foo=$false)
$foo.IsPresent
Run Code Online (Sandbox Code Playgroud)

当我运行这个:

.\test.ps1
Run Code Online (Sandbox Code Playgroud)

我收到错误:

无法在参数'foo'上处理参数转换.无法将"System.Management.Automation.SwitchParameter"类型的"False"值转换为"System.Management.Automation.ParameterAttribute"类型.

用它来称呼它

.\test.ps1 -foo
Run Code Online (Sandbox Code Playgroud)

我明白了

缺少参数'foo'的参数.指定"System.Management.Automation.ParameterAttribute"类型的参数,然后重试.

有谁知道为什么?

'parametersetname'有什么魔力呢?

Ale*_*les 6

您不需要使用parametersetname,但在参数之后需要括号.

如果省略括号,似乎powershell将其作为参数的类型信息读取并尝试将参数转换为该类型,而不是将其视为参数属性.

param([Parameter()][switch]$foo=$false)
Run Code Online (Sandbox Code Playgroud)

工作原样

param([switch]$foo=$false)
Run Code Online (Sandbox Code Playgroud)

  • 您不需要将默认值设置为false,布尔值当然默认为false而没有赋值.虽然没有实际的区别. (2认同)