从返回的PowerShell函数将调试消息打印到控制台

时间:2012-04-15 02:29:10

标签: debugging function powershell

有没有办法从返回值的PowerShell函数中将调试消息打印到控制台?

示例:

function A
{
    $output = 0

    # Start of awesome algorithm
    WriteDebug # Magic function that prints debug messages to the console
    #...
    # End of awesome algorithm

    return $output
}

# Script body
$result = A
Write-Output "Result=" $result

是否有符合此描述的PowerShell功能?

我知道Write-Output和Write- *,但在我的所有测试中,使用上述函数中的任何函数都不会编写任何调试消息。我也知道只是在不使用返回值的情况下调用函数确实会导致函数编写调试消息。

1 个答案:

答案 0 :(得分:8)

当然,使用Write-Debug cmdlet来执行此操作。请注意,默认情况下您将看不到调试输出。要查看调试输出,请将$DebugPreference设置为Continue(而不是SilentlyContinue)。对于简单的函数,我通常会这样做:

function A ([switch]$Debug) {
    if ($Debug) { $DebugPreference = 'Continue' }
    Write-Debug "Debug message about something"
    # Generate output
    "Output something from function"
}

请注意,我不建议使用return $output表单。函数输出未被变量捕获的任何内容,重定向到文件(或Out-Null)或强制转换为[void]。如果您需要提前从函数返回,请务必使用return

对于高级功能,您可以更轻松地获得调试功能,因为PowerShell为您提供了无处不在的参数,包括-Debug

function A {
    [CmdletBinding()]
    param()

    End {
        $pscmdlet.WriteDebug("Debug message")
        "Output something from cmdlet"
    }
}

仅供参考,[CmdletBinding()]语句中的param()属性是使其成为高级函数的原因。

如果您只想要一种输出与调试无关的其他信息,也不要忘记Write-Verbose$pscmdlet.WriteVerbose()

相关问题