Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Cmdlet, how can I detect if the Debug flag is set?

Tags:

c#

powershell

I'm writing a PowerShell Cmdlet and using WriteDebug, but I want to write an object which requires an extra API call, and I'd rather not make that call when debugging is turned off. How can I detect whether the Debug flag is set or not, so that I can skip this call to WriteDebug entirely?

For example, my WriteDebug call will look something like this:

WriteDebug(string.Format("Name : {0}", api.GetName(myobj)));

In that example, I want to avoid the call to api.GetName unless debugging is turned on.

like image 558
Ricket Avatar asked Mar 27 '12 18:03

Ricket


People also ask

What is the cmdlet used to send Debug information to the screen?

The Write-Debug cmdlet writes debug messages to the host from a script or command. By default, debug messages are not displayed in the console, but you can display them by using the Debug parameter or the $DebugPreference variable.

How do I enable Debug mode in PowerShell script?

Press F5 or, on the toolbar, click the Run Script icon, or on the Debug menu, click Run/Continue or, in the Console Pane, type C and then press ENTER .

How do I get out of Debug mode in PowerShell?

To exit the debugger, you can use Stop (q). Starting in PowerShell 5.0, you can run the Exit command to exit a nested debugging session that you started by running either Debug-Job or Debug-Runspace .

What does setting the step parameter in set PSDebug cmdlet achieve?

The Set-PSDebug cmdlet turns script debugging features on and off, sets the trace level, and toggles strict mode. By default, the PowerShell debug features are off. When the Trace parameter has a value of 1 , each line of script is traced as it runs.


1 Answers

Try this:

$Debug = $psboundparameters.debug.ispresent


if ($Debug){
  Write-Debug(string.Format("Name : {0}", api.GetName(myobj))
  }
like image 181
mjolinor Avatar answered Sep 26 '22 13:09

mjolinor