Alex G.
Alex G.

Reputation: 2153

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?

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.

Upvotes: 4

Views: 15316

Answers (1)

Keith Hill
Keith Hill

Reputation: 201712

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.

Upvotes: 10

Related Questions