PowerShell: Return Debug and Verbose messages From Your Functions

Debug and Verbose let you return extra information from your scripts, for specific situations, and only when needed. Debug lets you return “programmer-level” information. Verbose lets you return more detailed information to the user. I’ll provide some examples.

Suppose we are starting with this simple example, it returns True if the named services is running or False if it is not:

Verbose

To let us write verbose messages for this function, we have 2 choices. The first is the $VerbosePreference common variable. By default, it is set to “SilentlyContinue”. But if we set $VerbosePreference to “Continue”, we can write verbose messages.

Example code:

Example results:

Another way to use verbose messages is to use CmdletBinding to make your function an advanced function. Advanced functions automatically recognize common parameters like -Debug and -Verbose. You don’t need to change your function too much to make it “advanced”. You’ll need to add the CmdletBinding attribute. And you’ll need to put your function’s parameters in the Param attribute.

Example results:

Debug

Simular to verbose, to write debug messages, we have 2 choices. The first is the $DebugPreference common variable. By default, it is set to “SilentlyContinue”. But if we set $DebugPreference to “Continue”, we can write debug messages.

For example:

Example results:

Like verbose, we can make our function an advanced function with CmdletBinding to get debug messages. Again, you’ll need to add the CmdletBinding attribute and use the Param attribute. Unlike verbose, when you run the function with -Debug, in addition to seeing the debug message, the command pause for confirmation.

Code example:

Example results (PowerShell asks “Continue with this operation?” at each DEBUG):

Leave a Reply

Your email address will not be published. Required fields are marked *