3

有没有办法从返回值的 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-*,但是在我所有的测试中,在上述函数中使用任何这些函数都不会写入任何调试消息。我也知道只调用函数而不使用返回值确实会导致函数编写调试消息。

4

1 回答 1

9

当然,使用Write-Debugcmdlet 来执行此操作。请注意,默认情况下您不会看到调试输出。为了查看调试输出,设置$DebugPreferenceContinue(而不是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()如果您只是想要一种输出与调试无关的附加信息的方法。

于 2012-04-15T03:20:30.013 回答