【问题标题】:Powershell don't pass Verbosity level to called functionsPowershell 不会将详细级别传递给被调用函数
【发布时间】:2014-04-24 19:11:55
【问题描述】:

考虑以下脚本:

function a{
    [CmdletBinding()]
    Param()
    Write-Verbose "A VERBOSE"
    Write-Host "A NORMAL"
}

function b{
    [CmdletBinding()]
    Param()

    Write-Verbose "B VERBOSE"
    Write-Host "B NORMAL"

    a
}

b -Verbose

如果我们在指定详细参数开关的情况下调用函数“b”,则函数“a”(在“b”中调用)也会使用隐式详细参数调用。有没有办法避免这种情况? (换句话说,使用 Verbose 开关调用“b”,不使用它调用“a”)。

【问题讨论】:

    标签: debugging powershell scripting verbosity


    【解决方案1】:

    如果您想从外部函数 b 抑制 a 的详细输出,您可以使用 $PSDefaultParameterValues 变量,从 PowerShell v3 开始。

    function a{
        [CmdletBinding()]
        Param()
        Write-Verbose "A VERBOSE"
        Write-Host "A NORMAL"
    }
    
    function b{
        [CmdletBinding()]
        Param()
    
        Write-Verbose "B VERBOSE"
        Write-Host "B NORMAL"
    
        a
    }
    
    $PSDefaultParameterValues['a:Verbose'] = $False
    b -Verbose
    

    对于 PowerShell v2,当您从 b 函数调用 a 时,您必须将详细设置为 $False

    function b{
        [CmdletBinding()]
        Param()
    
        Write-Verbose "B VERBOSE"
        Write-Host "B NORMAL"
    
        a -Verbose:$false
    }
    

    【讨论】:

    • 使用 PS v3 可以得到 $PSDefaultParameterValues['a:Verbose'] = $False 但发现 a -Verbose:$false 方法工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    相关资源
    最近更新 更多