将可选参数传递给子例程而不实例化它们

时间:2017-07-13 09:39:13

标签: shell powershell scripting windows-scripting

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

现在我希望能够调用此脚本,同时在命令行中提供其中一些参数,将它们作为可选参数,并将它们传递给原始子例程。但是,在脚本的范围内,我可以测试参数是否与$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时被实例化,是否有更优雅/正确的方法来处理它?<​​/ p>

1 个答案:

答案 0 :(得分:2)

使用@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