powershell - 如何在 PowerShell 中为脚本提供参数属性?

标签 powershell parameters

我有一个可以通过两种方式调用的脚本:

MyScript -foo path\to\folder

MyScript -bar path\to\folder

(也就是说,我可以传递一个开关加一个文件夹或一个字符串参数加一个文件夹。)

我尝试输入 parameter declarations进入我的脚本以反射(reflect)该语法:

param(
  [parameter(Mandatory=$false)] [switch]$foo,
  [parameter(Mandatory=$false)] [String]$bar,
  [parameter(Mandatory=$true)]  [System.IO.FileInfo]$path
)

但是我必须显式传递 path 才能调用脚本:

MyScript -l -path path\to\folder

那么(如何)我可以同时制作 barpath 位置参数?

注意:如果我选择了一种非常愚蠢的语法来调用脚本,我仍然可以更改它。

最佳答案

有几件事:您需要使用参数集来告诉 PowerShell 有互斥的方式来调用您的脚本;也就是说,不能同时使用开关和字符串。这些集合还允许您将 $bar$filepath 的位置设置为索引 0。开关不需要按原样放置在位置上对 Binder 来说没有歧义,并且可以放置在任何地方。此外,每组中至少有一个参数应该是强制性的。

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 属性来指定哪个参数集应为默认值。

以下是上述配置的语法帮助:

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 - 如何在 PowerShell 中为脚本提供参数属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12424078/

相关文章:

ruby-on-rails - 向前传递所有参数?

swift - 为什么 Apple 选择使用嵌套结构类型来替换 'String' 类型参数?

bash - cd-vs cd ..说明

powershell - 在Powershell中将MailKit DLL作为程序集加载

c# - 当数据未与报表一起保存并导出为 PDF 时出现 ParameterFieldCurrentValueException

JAVA:向方法添加新参数

c# - 将任务作为要在异步方法 C# 中的循环内调用的参数传递

powershell - 处理来自PowerShell脚本的DISM错误

powershell - 组对象,获取计数

powershell - Pester:如何阻止我的脚本运行?