Print debug messages to console from a Powershell function that returns

Tag: debugging , function , powershell Author: love__sun Date: 2012-03-29

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.

Best Answer

Sure, use the Write-Debug cmdlet to do so. Note that by default you will not see debug output. In order to see the debug output, set $DebugPreference to 'Continue' (instead of SilentlyContinue). For simple functions I will usually do something like this:

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

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 use return.

For advanced functions you can get debug functionality a bit more easily because PowerShell provides the ubiquitous parameters for you, including -Debug:

function A {
    [CmdletBinding()]
    param()

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

FYI, it's the [CmdletBinding()] attribute on the param() statement is what makes this an advanced function.

Also don't forget about Write-Verbose and $pscmdlet.WriteVerbose() if you just want a way to output additional information that isn't debug related.

comments:

write-host works just as well, too.
@x0n Well yeah except that you don't much control over messages to the host. No shutting them off and no redirection to a log file. :-)
I see now. Thanks.
@KeithHill True, dat.