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?
$DebugPreference = 'Continue' to start seeing output from
When you're done, restore preference variable
$DebugPreference to its default value, using
$DebugPreference = 'SilentlyContinue'
To turn on debug output for a given cmdlet or advanced function only, use the
-Debug common parameter.
Whether output from
Write-Debug statements is printed is controlled by two mechanisms:
Scope-wide: by the value of the
$DebugPreference preference variable - see
Ad-hoc, command-scoped, when calling a cmdlet or advanced script/function (which overrides the
$DebugPreference value) with the
-Debug common parameter - see
$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:
in Windows PowerShell, you invariably set it to the value
Inquire, which not only prints
Write-Debug messages, but also pauses at every such statement to ask how you want to proceed.
in PowerShell [Core] v6+, the value is now (more sensibly) set to
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
$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.