【问题标题】:Passing optional parameters to subroutines without instantiating them将可选参数传递给子程序而不实例化它们
【发布时间】:2017-12-18 00:21:10
【问题描述】:

我有一个脚本提示用户输入(网址、用户名和密码等)并验证这些输入或再次提示用户。

现在我希望能够调用此脚本,同时在命令行上提供其中一些参数,将它们作为可选参数,并将它们传递给原始子例程。但是,在脚本的范围内,我可以测试是否提供了参数$PSBoundParameters.ContainsKey('a'),但是一旦我将参数$a(可能没有提供)传递给函数,相同的测试将始终返回$True.

示例代码:

function main {
    param (
        [string]$a
    )
    if ($PSBoundParameters.ContainsKey('a')) {
        "main - a is $a"
    }
    else {
        "main - didn't get a"
    }
    getStr $a
}

function getStr {
    param (
        [string]$a
    )
    if ($PSBoundParameters.ContainsKey('a')) {
        "getStr - a is $a"
    }
    else {
        "getStr - didn't get a"
    }
}

输入:

main

main "hello"

预期输出:

main - didn't get a
getStr - didn't get a

main - a is hello
getStr - a is hello

实际输出:

main - didn't get a
getStr - a is

main - a is hello
getStr - a is hello

我的猜测是 $a 在调用 getStr $a 时被实例化,有没有更优雅/正确的方法来处理这个问题?

【问题讨论】:

    标签: shell powershell scripting windows-scripting


    【解决方案1】:

    使用@PSBoundParameters。我修改了你的函数,所以我可以将它作为脚本运行。

    代码

    param (
        [string]$a
    )
    
    function main {
        param (
            [string]$a
        )
        if ($PSBoundParameters.ContainsKey('a')) {
            "main - a is $a"
        }
        else {
            "main - didn't get a"
        }
        getStr @PSBoundParameters
    }
    
    function getStr {
        param (
            [string]$a
        )
        if ($PSBoundParameters.ContainsKey('a')) {
            "getStr - a is $a"
        }
        else {
            "getStr - didn't get a"
        }
    }
    main @PSBoundParameters
    

    输出

    PS C:\> .\code.ps1 -a string
    main - a is string
    getStr - a is string
    PS C:\> .\code.ps1
    main - didn't get a
    getStr - didn't get a
    

    【讨论】:

    • 谢谢,这解决了上述问题。如果可以的话,我可能会得到几个参数,而每个子程序只需要检查一个呢?
    • 供将来参考 - 我自己对此进行了测试,我只是将 splatted (@) PSBoundVariables 发送到每个函数,它会检查它想要的密钥。
    猜你喜欢
    • 2016-11-22
    • 2019-01-18
    • 2015-04-04
    • 1970-01-01
    • 2012-04-14
    • 2017-09-16
    • 2017-08-05
    • 2023-03-03
    • 2013-07-11
    相关资源
    最近更新 更多