Zum Inhalt

Powershell – Colorize string output with colorvariables in the output string

The other day I saw a script output that was colored with magenta. I was a bit impressed by the readability of the output messages. As I looked to the source code I saw something (ugly) like:

The output looked like:

Powershell colorizing string output
Powershell colorizing string output

The Output is not so bad, but the effort is enormous. I came to the idea to encode the colorsettings within the output string. So I ended up with the following Script:

Now it’s possible to use a single string to encode the color by seperating each color with a hashtag (#).
Here is an example:

colorizing string output with colorvariables
colorizing string output with colorvariables

The syntax is very simple. Choose a color for the next characters and put it into hashtags (#). To stop coloring the characters just put another hashtag behind the colored characters to reset the foreground color to its default.

If you want to use any other charater, or command for the coloring, just replace the hashtag of the split function in line 20 with your character/command. I think this is a usefull function, because script output is often needed and coloring the important parts of the output is sometimes very helpful 🙂

Edit: I edited the script to work even if you pipe a string to write-chost like:
PS C:\> „#green# Everything is ok at #magenta#MyServer#“ | write-chost

Published inCodingPowershellScripting

Ein Kommentar

  1. Willy N Willy N

    This is a sweet–in other words, highly efficient–method of filtering & setting the colors as the strings are parsed! Great job! Thanks! 🙂

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

I accept that my given data and my IP address is sent to a server in the USA only for the purpose of spam prevention through the Akismet program.More information on Akismet and GDPR.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.