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?


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:

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:

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.


Print debug messages to console from a PowerShell function that returns by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply