问题描述
我有这个脚本,可以通过两种方式调用:
I have this script that can be called in two ways:
MyScript -foo path\to\folder
或
MyScript -bar path\to\folder
(也就是说,我可以传递一个开关加上一个文件夹,也可以传递一个字符串参数加上一个文件夹.)
(That is, I can either pass a switch plus a folder or a string argument plus a folder.)
我试图将参数声明放入我的脚本中以反映该语法:
I have tried to put parameter declarations into my script as to reflect that syntax:
param(
[parameter(Mandatory=$false)] [switch]$foo,
[parameter(Mandatory=$false)] [String]$bar,
[parameter(Mandatory=$true)] [System.IO.FileInfo]$path
)
但是随后我必须显式传递path
来调用脚本:
But then I have to pass path
explicitly to invoke the script:
MyScript -l -path path\to\folder
那么(如何)我可以同时做bar
和path
位置参数?
So (how) can I do that making both bar
and path
positional parameters?
注意:如果我选择了一种极其愚蠢的语法来调用脚本,我仍然可以对其进行更改.
Note: If I have picked an extraordinarily stupid syntax for invoking the script, I can still change it.
推荐答案
几件事:您需要使用参数集来告诉PowerShell有一些互斥的方式来调用脚本;也就是说,您不能同时使用开关和字符串.这些集合还使您可以将$bar
和$filepath
的位置都设置为索引0.开关不需要与活页夹不歧义,可以放置在任何位置,因此无需放置.同样,每组中至少应有一个参数是必需的.
A couple of things: You need to use parameter sets to tell PowerShell that there are mutually exclusive ways to invoke your script; that is to say, you cannot use the switch and the string at the same time. The sets also serve to allow you to set the position of both $bar
and $filepath
to be at index 0. Switches don't need to be positionally placed as they are not ambiguous to the binder and be placed anywhere. Also, at least one parameter in each set should be mandatory.
function test-set {
[CmdletBinding(DefaultParameterSetName = "BarSet")]
param(
[parameter(
mandatory=$true,
parametersetname="FooSet"
)]
[switch]$Foo,
[parameter(
mandatory=$true,
position=0,
parametersetname="BarSet"
)]
[string]$Bar,
[parameter(
mandatory=$true,
position=1
)]
[io.fileinfo]$FilePath
)
@"
Parameterset is: {0}
Bar is: '{1}'
-Foo present: {2}
FilePath: {3}
"@ -f $PSCmdlet.ParameterSetName, $bar, $foo.IsPresent, $FilePath
}
需要CmdletBinding
属性,以指定在没有 参数的情况下调用该函数时哪个参数集应为默认值.
The CmdletBinding
attribute is needed to specify which parameter set should be the default if the function is invoked without parameters.
以下是上述配置的语法帮助:
Here's the syntax help for the above configuration:
PS> test-set -?
NAME
test-set
SYNTAX
test-set [-Bar] <string> [-FilePath] <FileInfo> [<CommonParameters>]
test-set [-FilePath] <FileInfo> -Foo [<CommonParameters>]
这是各种调用的输出:
PS> test-set barval C:\temp\foo.zip
Parameterset is: BarSet
Bar is: 'barval'
-Foo present: False
FilePath: C:\temp\foo.zip
PS> test-set -foo c:\temp\foo.zip
Parameterset is: FooSet
Bar is: ''
-Foo present: True
FilePath: c:\temp\foo.zip
希望这会有所帮助.
这篇关于如何在PowerShell中为脚本提供参数属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!