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

Ale*_* G. 2 debugging powershell function

有没有办法从返回值的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
Run Code Online (Sandbox Code Playgroud)

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

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

Kei*_*ill 8

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

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

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

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

function A {
    [CmdletBinding()]
    param()

    End {
        $pscmdlet.WriteDebug("Debug message")
        "Output something from cmdlet"
    }
}
Run Code Online (Sandbox Code Playgroud)

仅供参考,声明中的[CmdletBinding()]属性param()是使其成为高级功能的原因.

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

  • @ x0n嗯,是的,除了你没有太多控制到主机的消息.不关闭它们,也不重定向到日志文件.:-) (3认同)