Using System Error Colors for Output

by Jan 12, 2015

All Versions

If your script wants to output warnings or error messages, you can use Write-Warning or Write-Error. Both cmdlets will use the default PowerShell colors for warnings and errors. However, the cmdlets will also apply a text template to your output:

 
PS> Write-Warning -Message 'This  is a warning'
WARNING: This is a warning
 
PS> Write-Error -Message  'Something went wrong'
Write-Error -Message 'Something went wrong'  : Something went wrong
    +  CategoryInfo          : NotSpecified: (:)  [Write-Error], WriteErrorException
    +  FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
  

Write-Error adds a lot of meaningless exception details when all you wanted was output some error text. A better way:

 
PS>  $host.UI.WriteErrorLine('Something went wrong...')
Something went wrong...
 

The colors for warnings and errors can be configured here by the way:

  
PS>  $host.UI.WriteErrorLine('Something went wrong...')
Something went wrong...

PS> $host.PrivateData.ErrorBackgroundColor  = 'White'

PS>  $host.UI.WriteErrorLine('Something went wrong...')
Something  went wrong...

PS> $host.PrivateData

(...)
ErrorForegroundColor                      : #FFFF0000
ErrorBackgroundColor                      : #FFFFFFFF
WarningForegroundColor                    : #FFFF8C00
WarningBackgroundColor                    : #00FFFFFF
VerboseForegroundColor                    : #FF00FFFF
VerboseBackgroundColor                    : #00FFFFFF
DebugForegroundColor                      : #FF00FFFF
DebugBackgroundColor                      : #00FFFFFF
(...)
 

Twitter This Tip! ReTweet this Tip!