Saturday, 26 August 2017

PowerShell functions with -Verbose and -Debug

Introduction

So, another rather standard day but made a little more interesting with some new tips on getting your PowerShell functions to provide some more feedback. We’re going to look at how to get your script to use the -Verbose and -Debug parameters.

Simple function

Okay, so our simple function is below. It just takes a Message parameter of and outputs Welcome <message> in green.

image

function Welcome
     {
         param(
             [string]$Message
             )

        Write-Host Welcome $message -ForegroundColor Green
     }

We can run the function as below:

Welcome -Message "to my blog!"

image

Nothing really that interesting here. Let’s move on.

Add -Verbose and -Debug to a PowerShell function

Here I’m adding another part to the script - [cmdletbinding()]. This automatically adds the -Verbose and -Debug parameters to the script and does all the logic behind it. By default, Write-Verbose doesn’t actually produce an output.

image

function Welcome
     {
         [cmdletbinding()] #This provides the function with the -Verbose and -Debug parameters
         param(
             [string]$Message
             )

        #Verbose - this is only shown if the -Verbose switch is used
         Write-Verbose -Message "This is verbose output"

        #Debug - this causes the script to halt at this point
         Write-Debug "This is debugging information"

        #Actual function
         Write-Host Welcome $message -ForegroundColor Green
     }

We can now run the function and specify the -Verbose parameter and we can see we’re now getting the output from Write-Verbose:

Welcome -Message "to my blog!" -Verbose

image

Let’s test out -Debug now. Debug is useful for when you’re debugging your script (who would have thought). Basically, it outputs Write-Debug, pauses the script and asks for you to either continue running it or to halt it. Write-Debug could contain more than just text. For example, if you want to check the value of a variable before it’s used, you can use Write-Debug to output the variable and then prompt you to either continue or halt the script.

Welcome -Message "to my blog!" -Debug

image

I selected Y and so it continued running the rest of the script:

image

So, there you have it. How to add -Verbose and -Debug into your functions.

No comments:

Post a Comment