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.
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.
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 .
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 .
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.
Try this:
$Debug = $psboundparameters.debug.ispresent
if ($Debug){
Write-Debug(string.Format("Name : {0}", api.GetName(myobj))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With