Is there a way to print debug messages to the console from a PowerShell function that returns a value?
Example:
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
Is there a PowerShell function that fits this description?
I’m aware of Write-Output and Write-*, but in all my tests using any of those functions inside a function like the one above will not write any debug messages. I’m also aware that just calling the function without using the returned value will indeed cause the function to write debug messages.
Sure, use the
Write-Debugcmdlet to do so. Note that by default you will not see debug output. In order to see the debug output, set$DebugPreferencetoContinue(instead ofSilentlyContinue). For simple functions I will usually do something like this:Note that I would not recommend using the form
return $output. Functions output anything that isn’t captured by a variable, redirected to a file (or Out-Null) or cast to[void]. If you need to return early from a function then by all means usereturn.For advanced functions you can get debug functionality a bit more easily because PowerShell provides the ubiquitous parameters for you, including
-Debug:FYI, it’s the
[CmdletBinding()]attribute on theparam()statement is what makes this an advanced function.Also don’t forget about
Write-Verboseand$pscmdlet.WriteVerbose()if you just want a way to output additional information that isn’t debug related.