PSColorText.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#requires -Version 3

function Write-ColorText
{
    <#
            .SYNOPSIS
            Writes text to the console using tags in the string itself
            to indicate the output color of the text. Can replace
            Write-Host cmdlet.
 
            .DESCRIPTION
            This script allows you to use custom markup to more easily
            write multi-colored text to the console. Can replace
            Write-Host cmdlet.
 
            It uses the general format of:
         
            !(foreground,background)
       
            to define a color setting.
 
            both background and foreground can be omitted, but the comma
            is required if you specify a background color.
            The following are all valid:
 
            !(red)
            !(,red)
            !(blue,)
            !(yellow,black)
 
            If you don't specify a color it will continue using the current
            color. If you specify "*" as a color it will revert to the default
            color.
 
            You can escape the markup using an additional '!':
 
            !!(red)
 
            .PARAMETER String
            The string to write out.
 
            .PARAMETER NoColor
            Disable color output.
 
            .PARAMETER NoNewLine
            Do not append a newline after writing out text.
 
            .PARAMETER ForegroundColor
            Initial Foreground color.
 
            .PARAMETER BackgroundColor
            Initial Background color.
 
            .EXAMPLE
            PS C:\> Write-ColorText "This is a test !(gray)[ !(red)fail!(gray) ]"
 
            .EXAMPLE
            PS C:\> Write-ColorText "This is a test !(gray)[!(black,green) fail !(gray,*)]"
 
            .INPUTS
            System.String
 
            .OUTPUTS
            None
    #>


    [CmdletBinding()]
    param(
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
        [System.String]
        $String,

        [ConsoleColor]
        $ForegroundColor,

        [ConsoleColor]
        $BackgroundColor,

        [switch]
        $NoNewline,

        [switch]
        $NoColor
    )
    
    begin 
    {
        function Test-Values
        {
            $matches = @($script:regex.Matches($String))
      
            # do some validation
            foreach ($match in $matches)
            {
                $foreground = $match.Groups['foreground'].Value.ToLower()
                $background = $match.Groups['background'].Value.ToLower()

                $success = $script:colors.Contains($foreground) -or $foreground -eq '*' -or $foreground -eq [string]::Empty
                if (!$success)
                {
                    $errorString = "Unrecognised Color: '{0}' : char: {1}`n" -f $foreground, $match.Index
                    $errorString += $String + "`n"
                    $errorString += (' ' * $match.Index) + ('~' * $match.Length)
                    throw $errorString
                }

                $success = $script:colors.Contains($background) -or $background -eq '*' -or $background -eq [string]::Empty
                if (!$success)
                {
                    $errorString = "Unrecognised Color: '{0}' : char: {1}`n" -f $background, $match.Index
                    $errorString += $String + "`n"
                    $errorString += (' ' * $match.Index) + ('~' * $match.Length)
                    throw $errorString
                }
            }
        } # function Test-Values

        function Resolve-Color
        {
            param($value, $bg = $false)

            if ($value -eq '*')
            {
                if ($bg)
                {
                    return $script:initialBackground
                }
                else
                {
                    return $script:initialForeground
                }
            }
            elseif ($value -eq [string]::Empty)
            {
                if ($bg)
                {
                    return $script:currentBackground
                }
                else
                {
                    return $script:currentForeground
                }
            }
      
            return $value
        } # Resolve-Color

        try 
        {
            $script:regex = [regex] '(?im)(?<!!)!\((?<foreground>(?:\w*|\*))(?:,(?<background>(?:\w*|\*)))?\)'
            $script:initialForeground = $host.UI.RawUI.ForegroundColor
            $script:initialBackground = $host.UI.RawUI.BackgroundColor

            $script:colors = [ConsoleColor].GetEnumNames() | ForEach-Object -Process {
                $_.ToLower()
            }
        } 
        catch 
        {
            throw
        }
    }
    process 
    {
        try 
        {
            if ($ForegroundColor)
            {
                $script:currentForeground = $ForegroundColor
            }
            else
            {
                $script:currentForeground = $script:initialForeground
            }

            if ($BackgroundColor)
            {
                $script:currentBackground = $BackgroundColor
            }
            else
            {
                $script:currentBackground = $script:initialBackground
            }

            Test-Values

            $matches = @($script:regex.Matches($String))
            $lastPos = 0

            foreach ($match in $matches)
            {
                if ($NoColor -or ($script:currentForeground.ToString() -eq '-1' -and $script:currentBackground.ToString() -eq '-1'))
                {
                    Write-Host -Object $String.Substring($lastPos, $match.Index - $lastPos) -NoNewline
                }
                elseif ($script:currentForeground.ToString() -eq '-1')
                {
                    Write-Host -Object $String.Substring($lastPos, $match.Index - $lastPos) -NoNewline -BackgroundColor $script:currentBackground
                }
                elseif ($script:currentBackground.ToString() -eq '-1')
                {
                    Write-Host -Object $String.Substring($lastPos, $match.Index - $lastPos) -NoNewline -ForegroundColor $script:currentForeground
                }
                else
                {
                    Write-Host -Object $String.Substring($lastPos, $match.Index - $lastPos) -NoNewline -BackgroundColor $script:currentBackground -ForegroundColor $script:currentForeground
                }

                $lastPos = $match.Index + $match.Length 
                $script:currentForeground = Resolve-Color $match.Groups['foreground'].Value $false
                $script:currentBackground = Resolve-Color $match.Groups['background'].Value $true
            }

            if ($NoColor -or ($script:currentForeground.ToString() -eq '-1' -and $script:currentBackground.ToString() -eq '-1'))
            {
                Write-Host -Object $String.Substring($lastPos) -NoNewline
            }
            elseif ($script:currentForeground.ToString() -eq '-1')
            {
                Write-Host -Object $String.Substring($lastPos) -BackgroundColor $script:currentBackground -NoNewline
            }
            elseif ($script:currentBackground.ToString() -eq '-1')
            {
                Write-Host -Object $String.Substring($lastPos) -ForegroundColor $script:currentForeground -NoNewline
            }
            else
            {
                Write-Host -Object $String.Substring($lastPos) -BackgroundColor $script:currentBackground -ForegroundColor $script:currentForeground -NoNewline
            }

            if (!$NoNewline.IsPresent)
            {
                Write-Host -Object ''
            }
        } 
        catch 
        {
            throw
        }
    }
    end 
    {
        try 
        {
            $host.UI.RawUI.ForegroundColor = $script:initialForeground
            $host.UI.RawUI.BackgroundColor = $script:initialBackground
        } 
        catch 
        {
            throw
        }
    }
}

Function Write-ColorLine
{
    <#
    .SYNOPSIS
        Utility to assemble a single line of colored text
        from component items.
    .DESCRIPTION
        Long description
    .EXAMPLE
    .INPUTS
        ColorLine Item(s)
        cf. New-ColorLineItem
    .OUTPUTS
    .NOTES
        A "powerline compatible" font is required to really
        benefit from this function.
    #>

    Param(
        [Parameter(Mandatory=$true)]
        [psobject[]]$items,
        [ConsoleColor]$defaultBackgroundColor = 'black',
        [String]$symbol =  '',
        [Switch]$NoNewLine
    )
        
    $back = $defaultBackgroundColor
        
    foreach ($item in $items)
    {
        $fore = $back
        $back = $item.bg
        Write-ColorText "!($fore,$back)$symbol" -NoNewLine
        $fore = $item.fg
        $back = $item.bg
        Write-ColorText ("!($fore,$back)" + $item.text) -NoNewline
    }
    Write-ColorText "!($back,$defaultBackgroundColor)$symbol" -NoNewLine:$NoNewLine
}

Function New-ColorLineItem
{
    <#
    .SYNOPSIS
        Utility to create a ColorLineItem custom object.
    .DESCRIPTION
        Easily create a color line obkect.
        These objects have the structure
        @{ bg, fg, text }
        where bg is the background color
        fg is the foreground color
        and text is the display text.
    .EXAMPLE
        C:\PS> <example usage>
        Explanation of what the example does
    .INPUTS
    .OUTPUTS
        PsCustomObject
    #>

    Param(
        [Parameter(Mandatory=$true)]
        [Alias('fg')]
        [ConsoleColor]$ForegroundColor,
            
        [Parameter(Mandatory=$true)]
        [Alias('bg')]
        [ConsoleColor]$BackgroundColor,
        
        [Parameter(Mandatory=$true)]
        [string]$Text
    )
        
    [PSCustomObject]@{fg = $ForegroundColor; bg = $BackgroundColor; text = $text};
}

Export-ModuleMember Write-ColorText, Write-ColorLine, New-ColorLineItem