PowerLine.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#!/usr/bin/env powershell
using namespace System.Collections.Generic
using namespace PoshCode.Pansies

$script:PowerLineRoot = $PSScriptRoot

if($PSVersionTable.PSVersion -lt "6.0") {
    Add-Type -Path $PSScriptRoot\lib\net451\PowerLine.dll
} else {
    Add-Type -Path $PSScriptRoot\lib\netstandard1.0\PowerLine.dll
}

if(!$PowerLinePrompt) {
    [PowerLine.Prompt]$Script:PowerLinePrompt = @(,@(
        @{ bg = "Cyan";     fg = "White"; text = { $MyInvocation.HistoryId } },
        @{ bg = "DarkBlue"; fg = "White"; text = { Get-SegmentedPath } }
    ))
}
function Add-PowerLineBlock {
    <#
        .Synopsis
            Insert a PowerLine block into the $PowerLinePrompt
        .Description
            Allows changing the foreground and background colors based on elevation or success.
 
            Tests elevation fist, and then whether the last command was successful, so if you pass separate colors for each, the Elevated*Color will be used when PowerShell is running as administrator and there is no error. The Error*Color will be used whenever there's an error, whether it's elevated or not.
        .Example
            New-PowerLineBlock (Get-Elapsed) -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow
 
            This example shows the time elapsed executing the last command in White on a DarkBlue background, but switches the text to yellow if elevated, and the background to red on error.
    #>

    [CmdletBinding(DefaultParameterSetName="Error")]
    param(
        # The text, object, or scriptblock to show as output
        [Parameter(Position=0, Mandatory=$true)]
        [Alias("Text")]
        $Object,

        # The foreground color to use when the last command succeeded
        [RgbColor]$ForegroundColor,

        # The background color to use when the last command succeeded
        [RgbColor]$BackgroundColor,

        # The foreground color to use when the process is elevated (running as administrator)
        [RgbColor]$ElevatedForegroundColor,

        # The background color to use when the process is elevated (running as administrator)
        [RgbColor]$ElevatedBackgroundColor,

        # The foreground color to use when the last command failed
        [RgbColor]$ErrorForegroundColor,

        # The background color to use when the last command failed
        [RgbColor]$ErrorBackgroundColor,

        # The line to insert the block to. Index starts at 0.
        # If the number is out of range, a new line will be added to the prompt
        # Defaults to -1 (the last line).
        [int]$Line = -1,

        # The column to insert the block to (Left or Right aligned).
        # Defaults to the Left column
        [ValidateSet("Left","Right")]
        [string]$Column = "Left",

        # The position in column to insert the block to. The left-aligned column is 0, the right-aligned column is 1.
        # Defaults to append at the end.
        [ValidateSet(-1,0,1)]
        [int]$InsertAt = -1
    )
    $Parameters = @{} + $PSBoundParameters
    # Remove the position parameters:
    $null = $Parameters.Remove("Line")
    $null = $Parameters.Remove("Column")
    $null = $Parameters.Remove("InsertAt")

    $blocks = [PowerLine.TextFactory]$Parameters

    if($Line -gt ($global:PowerLinePrompt.Lines.Count - 1)) {
        $null = $global:PowerLinePrompt.Add((New-Object PowerLine.Line))
        $Line = -1
    }

    [int]$Column = if($Column -eq "Left") { 0 } else { 1 }
    if($Column -gt ($global:PowerLinePrompt.Lines[$Line].Columns.Count - 1)) {
        $null = $global:PowerLinePrompt.Lines[$Line].Columns.Add((New-Object PowerLine.Column))
    }

    if($InsertAt -lt 0 -or $InsertAt -gt $global:PowerLinePrompt.Lines[$Line].Columns[$Column].Blocks.Count) {
        $global:PowerLinePrompt.Lines[$Line].Columns[$Column].Blocks.Add($blocks)
    } else {
        $global:PowerLinePrompt.Lines[$Line].Columns[$Column].Blocks.Insert($InsertAt,$blocks)
    }
}
function Get-Elapsed {
    <#
    .Synopsis
        Get the time span elapsed during the execution of command (by default the previous command)
    .Description
        Calls Get-History to return a single command and returns the difference between the Start and End execution time
    #>

    [CmdletBinding()]
    param(
        # The command ID to get the execution time for (defaults to the previous command)
        [Parameter()]
        [int]$Id,

        # A Timespan format pattern such as "{0:ss\.ffff}"
        [Parameter()]
        [string]$Format = "{0:h\:mm\:ss\.ffff}"
    )
    $null = $PSBoundParameters.Remove("Format")
    $LastCommand = Get-History -Count 1 @PSBoundParameters
    if(!$LastCommand) { return "" }
    $Duration = $LastCommand.EndExecutionTime - $LastCommand.StartExecutionTime
    $Format -f $Duration
}
function Get-SegmentedPath {
    <#
    .Synopsis
        Gets PowerLine Blocks for each folder in the path
    .Description
        Returns an array of hashtables which can be cast to PowerLine Blocks.
        Includes support for limiting the number of segments or total length of the path, but defaults to 3 segments max
    #>

    [CmdletBinding(DefaultParameterSetName="Segments")]
    param(
        # The path to segment. Defaults to $pwd
        [Parameter(Position=0)]
        [string]
        $Path = $pwd,

        # The maximum number of segments. Defaults to 3
        [Parameter(ParameterSetName="Segments")]
        $SegmentLimit = 3,

        # The maximum length. Defaults to 0 (no max)
        [Parameter(ParameterSetName="Length")]
        [int]
        $LengthLimit = 0,

        # The foreground color to use when the last command succeeded
        [RgbColor]$ForegroundColor,

        # The background color to use when the last command succeeded
        [RgbColor]$BackgroundColor,

        # The foreground color to use when the process is elevated (running as administrator)
        [RgbColor]$ElevatedForegroundColor,

        # The background color to use when the process is elevated (running as administrator)
        [RgbColor]$ElevatedBackgroundColor,

        # The foreground color to use when the last command failed
        [RgbColor]$ErrorForegroundColor,

        # The background color to use when the last command failed
        [RgbColor]$ErrorBackgroundColor
    )

    $buffer = @()

    if($Path.ToLower().StartsWith($Home.ToLower())) {
        $Path = '~' + $Path.Substring($Home.Length)
    }
    Write-Verbose $Path
    while($Path) {
        $buffer += if($Path -eq "~") {
            @{ Object = $Path }
        } else {
            @{ Object = Split-Path $Path -Leaf }
        }
        $Path = Split-Path $Path

        Write-Verbose $Path

        if($Path -and $SegmentLimit -le $buffer.Count) {
            if($buffer.Count -gt 1) {
                $buffer[-1] = @{ Object = [char]0x2026; }
            } else {
                $buffer += @{ Object = [char]0x2026; }
            }
            break
        }

        if($LengthLimit) {
            $CurrentLength = ($buffer.Object | Measure-Object Length -Sum).Sum + $buffer.Count - 1
            $Tail = if($Path) { 2 } else { 0 }

            if($LengthLimit -lt $CurrentLength + $Tail) {
                if($buffer.Count -gt 1) {
                    $buffer[-1] = @{ Object = [char]0x2026; }
                } else {
                    $buffer += @{ Object = [char]0x2026; }
                }
                break
            }
        }
    }
    [Array]::Reverse($buffer)

    foreach($output in $buffer) {

        # Always set the defaults first, if they're provided
        if($PSBoundParameters.ContainsKey("ForegroundColor")) {
            $output.ForegroundColor = $ForegroundColor
        }
        if($PSBoundParameters.ContainsKey("BackgroundColor")) {
            $output.BackgroundColor = $BackgroundColor
        }

        # If it's elevated, and they passed the elevated color ...
        if(Test-Elevation) {
            if($PSBoundParameters.ContainsKey("ElevatedForegroundColor")) {
                $output.ForegroundColor = $ElevatedForegroundColor
            }
            if($PSBoundParameters.ContainsKey("ElevatedBackgroundColor")) {
                $output.BackgroundColor = $ElevatedBackgroundColor
            }
        }

        # If it failed, and they passed an error color ...
        if(!(Test-Success)) {
            if($PSBoundParameters.ContainsKey("ErrorForegroundColor")) {
                $output.ForegroundColor = $ErrorForegroundColor
            }
            if($PSBoundParameters.ContainsKey("ErrorBackgroundColor")) {
                $output.BackgroundColor = $ErrorBackgroundColor
            }
        }
    }
    $buffer
}
function Get-ShortenedPath {
    [CmdletBinding()]
    param(
        [Parameter(Position=0)]
        [string]
        $Path = $pwd,

        [Parameter()]
        [switch]
        $RelativeToHome,

        [Parameter()]
        [int]
        $MaximumLength = [int]::MaxValue,

        [Parameter()]
        [switch]
        $SingleCharacterSegment        
    )

    if ($MaximumLength -le 0) {
        return [string]::Empty
    }

    if ($RelativeToHome -and $Path.ToLower().StartsWith($Home.ToLower())) {
        $Path = '~' + $Path.Substring($Home.Length)
    }

    if (($MaximumLength -gt 0) -and ($Path.Length -gt $MaximumLength)) {
        $Path = $Path.Substring($Path.Length - $MaximumLength)
        if ($Path.Length -gt 3) {
            $Path = "..." + $Path.Substring(3)
        }
    }

    # Credit: http://www.winterdom.com/powershell/2008/08/13/mypowershellprompt.html
    if ($SingleCharacterSegment) {
        # Remove prefix for UNC paths
        $Path = $Path -replace '^[^:]+::', ''
        # handle paths starting with \\ and . correctly
        $Path = ($Path -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2')
    }

    $Path
}
#set-alias New-PowerLineBlock New-TextFactory
function New-TextFactory {
    <#
        .Synopsis
            Create PowerLine.TextFactory with variable background colors
        .Description
            Allows changing the foreground and background colors based on elevation or success.
 
            Tests elevation fist, and then whether the last command was successful, so if you pass separate colors for each, the Elevated*Color will be used when PowerShell is running as administrator and there is no error. The Error*Color will be used whenever there's an error, whether it's elevated or not.
        .Example
            New-TextFactory (Get-Elapsed) -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow
 
            This example shows the time elapsed executing the last command in White on a DarkBlue background, but switches the text to yellow if elevated, and the background to red on error.
    #>

    [CmdletBinding(DefaultParameterSetName="Error")]
    param(
        # The text, object, or scriptblock to show as output
        [Alias("Text")]
        [AllowNull()][AllowEmptyString()]
        [Parameter(Position=0, ValueFromPipeline, ValueFromPipelineByPropertyName)] # , Mandatory=$true
        $Object,

        # The foreground color to use when the last command succeeded
        [Alias("Foreground", "Fg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ForegroundColor,

        # The background color to use when the last command succeeded
        [Alias("Background", "Bg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$BackgroundColor,

        # The foreground color to use when the process is elevated (running as administrator)
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ElevatedForegroundColor,

        # The background color to use when the process is elevated (running as administrator)
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ElevatedBackgroundColor,

        # The foreground color to use when the last command failed
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ErrorForegroundColor,

        # The background color to use when the last command failed
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ErrorBackgroundColor
    )
    $output = [PowerLine.TextFactory]@{
        Object = $Object
    }
    # Always set the defaults first, if they're provided
    if($PSBoundParameters.ContainsKey("ForegroundColor")) {
        $output.DefaultForegroundColor = $ForegroundColor
    }
    if($PSBoundParameters.ContainsKey("BackgroundColor")) {
        $output.DefaultBackgroundColor = $BackgroundColor
    }

    # If it's elevated, and they passed the elevated color ...
    if(Test-Elevation) {
        if($PSBoundParameters.ContainsKey("ElevatedForegroundColor")) {
            $output.DefaultForegroundColor = $ElevatedForegroundColor
        }
        if($PSBoundParameters.ContainsKey("ElevatedBackgroundColor")) {
            $output.DefaultBackgroundColor = $ElevatedBackgroundColor
        }
    }

    # If it failed, and they passed an error color ...
    if(!(Test-Success)) {
        if($PSBoundParameters.ContainsKey("ErrorForegroundColor")) {
            $output.DefaultForegroundColor = $ErrorForegroundColor
        }
        if($PSBoundParameters.ContainsKey("ErrorBackgroundColor")) {
            $output.DefaultBackgroundColor = $ErrorBackgroundColor
        }
    }

    $output.GetText()
}
function Set-PowerLinePrompt {
    #.Synopsis
    # Set the default PowerLine prompt function which uses the $PowerLinePrompt variable
    #.Description
    # Overwrites the current prompt function with one that uses the PowerLinePrompt variable
    # Note that this doesn't try to preserve any changes already made to the prompt by modules like ZLocation
    #.Example
    # Set-PowerLinePrompt -CurrentDirectory
    #
    # Sets the powerline prompt and activates and option supported by this prompt function to update the .Net environment with the current directory each time the prompt runs.
    #.Example
    # Set-PowerLinePrompt -PowerLineFont
    #
    # Sets the powerline prompt using the actual PowerLine font characters, and ensuring that we're using the default characters. Note that you can still change the characters used to separate blocks in the PowerLine output after running this, by setting the static members of [PowerLine.Prompt] like Separator and ColorSeparator...
    #.Example
    # Set-PowerLinePrompt -ResetSeparators
    #
    # Sets the powerline prompt and forces the use of "safe" separator characters. You can still change the characters used to separate blocks in the PowerLine output after running this, by setting the static members of [PowerLine.Prompt] like Separator and ColorSeparator...
    #.Example
    # Set-PowerLinePrompt -UseAnsiEscapes
    #
    # Sets the powerline prompt and forces the use of ANSI escape sequences in the string output (rather than Write-Host) to change colors, regardless of what we're able to detect about the console.
    [CmdletBinding(DefaultParameterSetName="PowerLine")]
    param(
        # A script which outputs a string used to update the Window Title each time the prompt is run
        [scriptblock]$Title,

        # Keep the .Net Current Directory in sync with PowerShell's
        [switch]$CurrentDirectory,

        # If true, set the [PowerLine.Prompt] static members to extended characters from PowerLine fonts
        [Parameter(ParameterSetName="PowerLine")]
        [switch]$PowerLineFont,

        # If true, set the [PowerLine.Prompt] static members to characters available in Consolas and Courier New
        [Parameter(ParameterSetName="Reset")]
        [switch]$ResetSeparators,

        # If true, override the default testing for ANSI consoles and force the use of Escape Sequences rather than Write-Host
        [Parameter()]
        [switch]$UseAnsiEscapes = $($Host.UI.SupportsVirtualTerminal -or $Env:ConEmuANSI -eq "ON"),

        # If true, adds ENABLE_VIRTUAL_TERMINAL_PROCESSING to the console output mode. Useful on PowerShell versions that don't restore the console
        [Parameter()]
        [switch]$RestoreVirtualTerminal
    )
    if($null -eq $script:OldPrompt) {
        $script:OldPrompt = $function:global:prompt
        $MyInvocation.MyCommand.Module.OnRemove = {
            $function:global:prompt = $script:OldPrompt
        }
    }
    if($PSBoundParameters.ContainsKey("Title")) {
        $global:PowerLinePrompt.Title = $Title
    }
    if($PSBoundParameters.ContainsKey("CurrentDirectory")) {
        $global:PowerLinePrompt.SetCurrentDirectory = $CurrentDirectory
    }

    $global:PowerLinePrompt.UseAnsiEscapes = $UseAnsiEscapes
    $global:PowerLinePrompt.RestoreVirtualTerminal = $RestoreVirtualTerminal


    if($ResetSeparators -or ($PSBoundParameters.ContainsKey("PowerLineFont") -and !$PowerLineFont) ) {
        # Use characters that at least work in Consolas
        [PowerLine.Prompt]::ColorSeparator  = [char]0x258C
        [PowerLine.Prompt]::ReverseColorSeparator = [char]0x2590
        [PowerLine.Prompt]::Separator  = [char]0x25BA
        [PowerLine.Prompt]::ReverseSeparator = [char]0x25C4
        [PowerLine.Prompt]::Branch   = [char]0x00A7
        [PowerLine.Prompt]::Gear     = [char]0x263C
    }
    if($PowerLineFont) {
        # Make sure we're using the PowerLine custom use extended characters:
        [PowerLine.Prompt]::ColorSeparator = [char]0xe0b0
        [PowerLine.Prompt]::ReverseColorSeparator = [char]0xe0b2
        [PowerLine.Prompt]::Separator = [char]0xe0b1
        [PowerLine.Prompt]::ReverseSeparator = [char]0xe0b3
        [PowerLine.Prompt]::Branch   = [char]0xE0A0
        [PowerLine.Prompt]::Gear     = [char]0x26EF
    }

    $function:global:prompt =  {

        # FIRST, make a note if there was an error in the previous command
        [bool]$script:LastSuccess = $?

        try {
            if($global:PowerLinePrompt.Title) {
                $Host.UI.RawUI.WindowTitle = [System.Management.Automation.LanguagePrimitives]::ConvertTo( (& $global:PowerLinePrompt.Title), [string] )
            }
            if($global:PowerLinePrompt.SetCurrentDirectory) {
                # Make sure Windows & .Net know where we are
                # They can only handle the FileSystem, and not in .Net Core
                [System.IO.Directory]::SetCurrentDirectory( (Get-Location -PSProvider FileSystem).ProviderPath )
            }
        } catch {}

        if ($global:PowerLinePrompt.RestoreVirtualTerminal) {
            [PoshCode.Pansies.Console.WindowsHelper]::EnableVirtualTerminalProcessing()
        }
        $global:PowerLinePrompt.ToString($Host.UI.RawUI.BufferSize.Width)
    }
}
function Test-Elevation {
    <#
    .Synopsis
        Get a value indicating whether the process is elevated (running as administrator)
    #>

    [CmdletBinding()]
    param()

    [Security.Principal.WindowsIdentity]::GetCurrent().Owner -eq 'S-1-5-32-544'
}
function Test-Success {
    <#
    .Synopsis
        Get a value indicating whether the last command succeeded or not
    #>

    [CmdletBinding()]
    param()

    $script:LastSuccess
}