|
| 1 | +<# |
| 2 | +.SYNOPSIS |
| 3 | +Colored console output |
| 4 | +
|
| 5 | +.DESCRIPTION |
| 6 | +Print colored text on the console. |
| 7 | +To specify the color you have to use color tags |
| 8 | +
|
| 9 | +.PARAMETER Text |
| 10 | +The text to print |
| 11 | +
|
| 12 | +.EXAMPLE |
| 13 | +Write-ColoredOutput -Text "uncolored text<blue>blue text</>uncolored text<green>green text</>" |
| 14 | +#> |
| 15 | +function Write-ColoredOutput() { |
| 16 | + param ( |
| 17 | + [string]$Text = '' |
| 18 | + ); |
| 19 | + |
| 20 | + <# |
| 21 | + Define opening and closing tag and build regex |
| 22 | + Example <red>text</> |
| 23 | + #> |
| 24 | + $colorTagOpen = '<'; |
| 25 | + $colorTagClose = '>'; |
| 26 | + $regexEndTag = '</>'; |
| 27 | + $regexStartTag = [string]::Format('{0}[A-Za-z]+{1}', $colorTagOpen, $colorTagClose); |
| 28 | + $textParts = [regex]::Split($Text, "($regexStartTag.*?$regexEndTag)"); |
| 29 | + |
| 30 | + |
| 31 | + # Loop over all parts |
| 32 | + foreach ($part in $textParts) { |
| 33 | + |
| 34 | + # Check if current part is color tagged |
| 35 | + if ($part -match "^$regexStartTag.*?$regexEndTag$") { |
| 36 | + |
| 37 | + # Get color tag |
| 38 | + $colorTag = [regex]::Matches($cuttedPart, $regexStartTag).Value; |
| 39 | + |
| 40 | + # Get color out of color tag |
| 41 | + $color = $colorTag.substring($colorTagOpen.Length, $colorTag.Length - ($colorTagOpen.Length + $colorTagClose.Length)); |
| 42 | + |
| 43 | + # Cut opening tag |
| 44 | + $finalPart = $cuttedPart.substring($colorTag.Length, $cuttedPart.length - $colorTag.Length); |
| 45 | + |
| 46 | + # Cut closing tag |
| 47 | + $cuttedPart = $part.substring(0, $part.Length - $regexEndTag.Length); |
| 48 | + |
| 49 | + <# |
| 50 | + Try colored printing. If color does not exist, |
| 51 | + catch runtime error and simply print normal |
| 52 | + #> |
| 53 | + try { |
| 54 | + Write-Host -NoNewline -ForegroundColor $color $finalPart; |
| 55 | + } catch { |
| 56 | + Write-Host -NoNewline $part; |
| 57 | + } |
| 58 | + |
| 59 | + continue; |
| 60 | + } |
| 61 | + |
| 62 | + # Print non tagged, uncolored part |
| 63 | + Write-Host -NoNewline $part; |
| 64 | + } |
| 65 | +} |
0 commit comments