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

Debugging 从返回的PowerShell函数将调试消息打印到控制台,debugging,function,powershell,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 bod

是否有方法将调试消息从返回值的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 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"
    }
}
仅供参考,
param()
语句中的
[CmdletBinding()]
属性使此函数成为高级函数


如果您只想获得一种输出与调试无关的附加信息的方法,请不要忘记
编写详细的
$pscmdlet.WriteVerbose()

@x0n是的,只是您对发送到主机的消息没有太多控制权。不关闭它们,也不重定向到日志文件。:-)