当前位置 博文首页 > PowerShell函数参数设置成自动识别数据类型的例子

    PowerShell函数参数设置成自动识别数据类型的例子

    作者:洪哥 时间:2021-02-07 21:21

    本文介绍PowerShell自定义函数中使用参数集时,怎么设置系统自动识别参数的数据类型。

    识别参数类型的一个好处就是,在使用参数集时,不需要每次都指定参数名称了。

    请看下面这个Test-Binding函数。这个PowerShell函数在设置参数集的时候,为参数集中的第一个参数设置了数据类型,这样在调用函数时,就可以自动判断一个参数值它应该赋给哪个参数了。

    复制代码 代码如下:

    function Test-Binding {
        [CmdletBinding(DefaultParameterSetName='Name')]
        param(
            [Parameter(ParameterSetName='ID', Position=0, Mandatory=$true)]
            [Int]
            $id,
            [Parameter(ParameterSetName='Name', Position=0, Mandatory=$true)]
            [String]
            $name
        )
        $set = $PSCmdlet.ParameterSetName
        “You selected $set parameter set”
        if ($set -eq ‘ID') {
            “The numeric ID is $id”
        } else {
            “You entered $name as a name”
        }
    }

    注意函数中参数$id上面的[int]和参数$name上面的[String]。有这了这样的函数定义,那我们在调用时就方便了,如果传一个字符串给它,它会把这个参数当作是$name,而传一个数字给它,这个参数会被当作是$id。且看如下调用函数的示例。
    复制代码 代码如下:

    PS> Test-Binding -Name hallo
    You selected Name parameter set
    You entered hallo as a name
    PS> Test-Binding -Id 12
    You selected ID parameter set
    The numeric ID is 12
    PS> Test-Binding hallo
    You selected Name parameter set
    You entered hallo as a name
    PS> Test-Binding 12
    You selected ID parameter set
    The numeric ID is 12

    上面一共做了4次调用,前两次调用都指定了参数名,没有什么好说的。后面两次都没有指定参数名称,但执行的结果跟前两次一模一样,这表示PowerShell函数自动识别了输入参数要调用的哪个参数名称。

    关于PowerShell函数参数集自动识别参数数据类型,本文就介绍这么多,希望对您有所帮助,谢谢!

    js
    下一篇:没有了