Creating a PowerShell Function to display error messages

Share this:

When writing your code using PowerShell, and based on the complexity of the script we need to create output to troubleshoot/debug the code.

We can always write-host “xxx” and see what is going on during the execution of the script, also the PowerShell ISE we can debug from the editor using F9 (Toggle Breakpoint) as well.


In this Tutorial, we will create a function that display the information based on the severity, we just need to pass the text and the severity where 0=normal, 1=warning, and 2=critical.

We control the display of the messages using a Global variable called $Global:vDebug, if we turn that to off, we automatically silence any message using the function.

Here is the Function, global variable and a basic example

$Global:vDebug = $True

Function APDebug ($param_ErrorMessage,$param_type)
     Switch ($param_type)
         0 {$vColor = “Cyan”; $vPreText = “-> “}
         1 {$vColor = “Yellow”; $vPreText = “.:. WARNING –> “}
         2 {$vcolor = “red”; $vPreText = “.:. ERROR –> “}

    If ($Global:vDebug)
         Write-Host -Foregroundcolor $vColor $vPretext $param_ErrorMessage

APDebug “Warning message” 1

We can test running the following command lines to see the results.


If we change the vDebug variable to false, automatically we don’t see output for the function. Which can be helpful during troubleshooting where you want to place your debug messages across the code and before deleting your code, we can disable the debug, see if everything is fine.

Using a function also helps when releasing that code to production, we just need to search and remove the lines used by the function, instead of evaluating write-host lines to see if they are debug or actual output from the script.


Written by Anderson Patricio

Anderson Patricio

Anderson Patricio is a Canadian MVP in Cloud and Datacenter Management, and Office Server and Services, besides the Microsoft Award he also holds a Solutions Master (MCSM) in Exchange and several other certifications. Anderson has been contributing to the Microsoft Community with articles, tutorials, blog posts, twitter, forums and book reviews. He is a regular contributor here at,, and Anderson (Portuguese).