With PowerShell, how can I get Write-Debug output to appear in the console?

I'm learning PowerShell and was using Write-Host to check variable assignments in a new PowerShell script file. Then I read an article suggesting this was a bad idea.

So, in my .ps1 file I replaced statements like this:

Write-Host "Start"
Write-Host "End"

... with this:

Write-Debug "Start"
Write-Debug "End"

But when I ran the saved script in Windows PowerShell ISE no output was written to the console. I appended -debug to the statement that calls the script, like so:

PS E:\trialrun> .\MyScript.ps1 -debug

But again, the output doesn't get written to the console. Apparently I'm using Write-Debug incorrectly. How can I get the debug output to write to the console?


  • tl;dr:

    Whether output from Write-Debug statements is printed is controlled by two mechanisms:

    $DebugPreference defaults to SilentlyContinue, which explains why you don't see any output from Write-Debug statements by default.

    When you use common parameter -Debug, you effectively set $DebugPreference for the invoked command only, and:

    Since, in Windows PowerShell, this prompt-at-every-Write-Debug-call behavior can be disruptive, $DebugPreference = 'Continue' may be the better approach. As stated, in PowerShell [Core] v6+ this is no longer a concern.

    Note: If, from inside an advanced function or script, you want to distinguish between $DebugPreference having been set as a preference variable by the caller vs. common parameter -Debug having been passed (which is translated to a function/script-local $DebugPreference variable), use $PSBoundParameters.ContainsKey('Debug'); $true indicates that -Debug was used.

    Reference official documentation: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-debug

    By default, debug messages are not displayed in the console, but you can display them by using the Debug parameter or the $DebugPreference variable.