Ever need to create a warning or error messages in powershell? Unfortunately the functionality isn’t built in to make it pretty. Fortunately its simple to fix with a few system objects and a function. The function below leverages powershells built in variables to deal with its coloring, it first saves your default colors to revert back to after running. It than sets the colors to the specified colors, sends the message to the console, and then reverts the colors back to default.
function WarningCustomOutput($message, [System.ConsoleColor]$foregroundcolor, [System.ConsoleColor]$backgroundcolor)
$currentColor = $Host.UI.RawUI.ForegroundColor
$currentbackground = $Host.UI.RawUI.Backgroundcolor
$Host.UI.RawUI.ForegroundColor = $foregroundcolor
$Host.UI.RawUI.Backgroundcolor = $backgroundcolor
$Host.UI.RawUI.ForegroundColor = $currentColor
$Host.UI.RawUI.Backgroundcolor = $currentbackground
Its important to notice the difference between Write-Output and Write-Host, I’ve left them both there just as a reminder.
$Warning = "WARNING!"
WarningCustomOutput -message "$Warning" -foregroundcolor yellow -backgroundcolor DarkMagenta
The function can be called many ways but to simply test it the above will work. Hope that helps!