递归-Powershell中的详细信息



是否有一种简单的方法可以使-Verbose开关"直通"Powershell中的其他函数调用?

我知道我可能可以在$PSBoundParameters中搜索该标志并执行if语句:

[CmdletBinding()]
Function Invoke-CustomCommandA {
    Write-Verbose "Invoking Custom Command A..."
    if ($PSBoundParameters.ContainsKey("Verbose")) {
        Invoke-CustomCommandB -Verbose
    } else {
        Invoke-CustomCommandB
    }
}
Invoke-CustomCommandA -Verbose

然而,这样做似乎相当混乱和多余。。。想法?

一种方法是在高级函数的顶部使用$PSDefaultParameters:

$PSDefaultParameterValues = @{"*:Verbose"=($VerbosePreference -eq 'Continue')}

然后,使用-Verbose参数调用的每个命令都将根据调用高级函数时是否使用-Verbose进行设置。

如果你只有几个命令,请这样做:

$verbose = [bool]$PSBoundParameters["Verbose"]
Invoke-CustomCommandB -Verbose:$verbose

我开始在一些powershell模块中使用KeithHill的$PSDefaultParameterValues技术。我遇到了一些非常令人惊讶的行为,我很确定这是由于scope和$PSDefaultParameterValues是一种全局变量的影响。我最终编写了一个名为Get-CommonParameters(别名gcp)的cmdlet,并使用splat参数来实现-Verbose(和其他常见参数)的显式和简洁级联。下面是一个例子:

function f1 {
    [CmdletBinding()]
    param()
    process
    {
        $cp = &(gcp)
        f2 @cp
        # ... some other code ...
        f2 @cp
    }
}
function f2 {
    [CmdletBinding()]
    param()
    process
    {
        Write-Verbose 'This gets output to the Verbose stream.'
    }
}
f1 -Verbose

cmdlet Get-CommonParameters(别名gcp)的源在此github存储库中。

怎么样:

$vb = $PSBoundParameters.ContainsKey('Verbose')
Invoke-CustomCommandB -Verbose:$vb

相关内容

最新更新