PowerShell debugging - by The Razor of Occam

Status : 


Sign in
to vote
ID 830670 Comments
Status Active Workarounds
Type Suggestion Repros 0
Opened 3/8/2014 8:39:31 PM
Access Restriction Public


I personally prefer to write debugging options into my functions. For example:

function Test-Example {
  [Parameter(mandatory=$false)][switch]$test <#I'd prefer to use the parameter name 'debug' but that's an environment
                                                                              inherited value, so I can't#>

 if($test){ [Console]::WriteLine("Computername is: ", $ComputerName)
[additional statements and condition checks here]
if($test) { [Console]::WriteLine("Additional output here")

I have to perform a parameter check because otherwise, I'd have to use Write-Debug, which means I'd have to turn it back off if any additional functions were called. Hell, it means it would be environmentally turned on. ANY function that contains a Write-Debug function from then on throws debug messages.

I can a) manually turn off debugging after every throw, or b) just if statement a new parameter.

perhaps we could have debugging turned off after every write-debug function by default. Or maybe a new cast? Something like:

Sign in to post a comment.
Posted by Martin Schvartzman on 5/18/2014 at 12:09 PM
Since you are not really writing anything to the debug stream, it seems more logical (and simple) to use the Verbose switch.

function Test-Example {
    Write-Verbose "ComputerName is $ComputerName"
    # [additional statements and condition checks here]
    Write-Verbose 'Additional output here'

Test-Example -ComputerName myComputer -Verbose
Posted by Kirk Munro on 4/22/2014 at 10:39 AM
I don't think you quite understand how this works.

If you invoke a function with -Debug, then $DebugPreference is set to "Inquire" within the context of that function and any functions/commands it calls only. It is not globally set affecting all functions.

For the functionality you are looking for, try this approach:

# In the top of your function, define this:
$debugging = @('Inquire','SilentlyContinue') -notcontains $DebugPreference

Then, in your function body you can do this:

if ($debugging) {Write-Host "ComputerName is: ${ComputerName}")}
if ($debugging) {Write-Host "Additional output here"}

With this approach, the logic inside of your if statements will only be invoked $DebugPreference is set to 'Continue','Stop', or 'Inquire'. This will happen if it is manually set in a parent scope or if the function is invoked with -debug or if a command calling this function was invoked with -debug.

I think what you are really looking for is this:

If that is the case, vote it up so that it is higher on the priority list of requests.