Print debug messages to console from a PowerShell function that returns

Is there a way to print debug messages to the console from a PowerShell function that returns a value?


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-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 {

    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.

Need Your Help

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

java php android json nullpointerexception

I was already reading the data from my database to android. I copied the code and used it again in my other app it gave me this error.

Bad http connection (400) from Simple Native Iphone App to test .net Web Service

.net iphone web-services iis

I have written a simple hello world .net web service which will accept 2 parameters and return the parameters as a string.