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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
#!/usr/bin/env powershell
using namespace System.Management.Automation
using namespace System.Collections.Generic
using namespace PoshCode.Pansies

Add-Type @'
using System;
using System.Management.Automation;
public class EmptyStringAsNullAttribute : ArgumentTransformationAttribute
{
    public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
    {
        if (inputData is string && ((string)inputData).Length == 0)
        {
            return null;
        }
        else
        {
            return inputData;
        }
    }
}
'@


# Ensure the global prompt variable exists and is typed the way we expect
[System.Collections.Generic.List[ScriptBlock]]$Global:Prompt = [ScriptBlock[]]@(
    if(Test-Path Variable:Prompt) {
        $Prompt | ForEach-Object { $_ }
    }
)

Add-MetadataConverter @{ [char] = { "'$_'" } }
function InitializeColor {
    [CmdletBinding()]
    param(
        [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$Colors = $Global:Prompt.Colors,

        [switch]$Passthru
    )

    if(!$PSBoundParameters.ContainsKey("Colors")){
        [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$Colors = if($global:Prompt.Colors) {
            $global:Prompt.Colors
        } else {
            "Cyan","DarkCyan","Gray","DarkGray","Gray"
        }
    }
    if($Passthru) {
        $Colors
    }

    if(!(Get-Member -InputObject $Global:Prompt -Name Colors)) {
        Add-Member -InputObject $Global:Prompt -MemberType NoteProperty -Name Colors -Value $Colors
    } else {
        $Global:Prompt.Colors = $Colors
    }
}
function prompt {
    # FIRST, make a note if there was an error in the previous command
    [bool]$script:LastSuccess = $?

    # Then handle PowerLinePrompt Features:
    if ($Script:PowerLineConfig.Title) {
        try {
            $Host.UI.RawUI.WindowTitle = [System.Management.Automation.LanguagePrimitives]::ConvertTo( (& $Script:PowerLineConfig.Title), [string] )
        } catch {
            Write-Error "Failed to set Title from scriptblock { $($Script:PowerLineConfig.Title) }"
        }
    }
    if ($Script:PowerLineConfig.SetCurrentDirectory) {
        try {
            # 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 {
            Write-Error "Failed to set CurrentDirectory to: (Get-Location -PSProvider FileSystem).ProviderPath"
        }
    }
    if ($Script:PowerLineConfig.RestoreVirtualTerminal -and (-not $IsLinux -and -not $IsMacOS)) {
        [PoshCode.Pansies.Console.WindowsHelper]::EnableVirtualTerminalProcessing()
    }

    # Evaluate all the scriptblocks in $prompt
    $UniqueColorsCount = 0
    $PromptText = @(
        foreach ($block in $Global:Prompt) {
            $block = & $block
            $buffer = $(
                if($block -as [PoshCode.Pansies.Text[]]) {
                    [PoshCode.Pansies.Text[]]$block
                } else {
                    [PoshCode.Pansies.Text[]][string[]]$block
                }
            ).Where{ ![string]::IsNullOrEmpty($_.Object) }

            # Each $buffer gets a color, if it needs one (it's not whitespace)
            $UniqueColorsCount += [bool]$buffer.Where({![string]::IsNullOrWhiteSpace($_.Object) -and $_.BackgroundColor -eq $null -and $_.ForegroundColor -eq $null }, 1)
            , $buffer
        }
    ).Where{ $_.Object }

    # When someone sets $Prompt, they loose the colors.
    # To fix that, we cache the colors whenever we get a chance
    # And if it's not set, we re-initialize from the cache
    if(!$Global:Prompt.Colors) {
        InitializeColor
    }
    # Based on the number of text blocks, get a color gradient or the user's color choices
    [PoshCode.Pansies.RgbColor[]]$Colors = @(
        if ($Global:Prompt.Colors.Count -ge $UniqueColorsCount) {
            $Global:Prompt.Colors
        } elseif ($Global:Prompt.Colors.Count -eq 2) {
            Get-Gradient ($Global:Prompt.Colors[0]) ($Global:Prompt.Colors[1]) -Count $UniqueColorsCount -Flatten
        } else {
            $Global:Prompt.Colors * ([Math]::Ceiling($UniqueColorsCount/$Global:Prompt.Colors.Count))
        }
    )

    # Loop through the text blocks and set colors
    $ColorIndex = 0
    foreach ($block in $PromptText) {
        $ColorUsed = $False
        foreach ($b in @($block)) {
            if (![string]::IsNullOrWhiteSpace($b.Object) -and $b.BackgroundColor -eq $null) {
                $b.BackgroundColor = $Colors[$ColorIndex]
                $ColorUsed = $True
            }
        }
        $ColorIndex += $ColorUsed

        foreach ($b in @($block)) {
            if ($b.BackgroundColor -ne $null -and $b.ForegroundColor -eq $null) {
                if($Script:PowerLineConfig.FullColor) {
                    $b.ForegroundColor = Get-Complement $b.BackgroundColor -ForceContrast
                } else {
                    $b.BackgroundColor, $b.ForegroundColor = Get-Complement $b.BackgroundColor -ConsoleColor -Passthru
                }
            }
        }
    }

    ## Finally, unroll all the output and join into one string (using separators and spacing)
    $Buffer = $PromptText | % { $_ }
    $line = ""
    $result = ""
    $RightAligned = $False
    $BufferWidth = [Console]::BufferWidth
    $ColorSeparator = "&ColorSeparator;"
    $Separator = "&Separator;"
    $LastBackground = $null
    for ($b = 0; $b -lt $Buffer.Count; $b++) {
        $block = $Buffer[$b]
        $string = $block.ToString()
        #Write-Debug "STEP $b of $($Buffer.Count) [$(($String -replace "\u001B.*?\p{L}").Length)] $($String -replace "\u001B.*?\p{L}" -replace "`n","{newline}" -replace "`t","{tab}")"

        ## Allow `t to split into (2) columns:
        if ($string -eq "`t") {
            if($LastBackground) {
                ## Before the (column) break, add a cap
                #Write-Debug "Pre column-break, add a $LastBackground cap"
                $line += [PoshCode.Pansies.Text]@{
                    Object          = "$ColorSeparator "
                    ForegroundColor = $LastBackground
                    BackgroundColor = $Host.UI.RawUI.BackgroundColor
                }
            }
            $result += $line
            $line = ""
            $RightAligned = $True
            $ColorSeparator = "&ReverseColorSeparator;"
            $Separator = "&ReverseSeparator;"
            $LastBackground = $Host.UI.RawUI.BackgroundColor
        ## Allow `n to create multi-line prompts
        } elseif ($string -in "`n", "`r`n") {
            if($RightAligned) {
                ## This is a VERY simplistic test for escape sequences
                $lineLength = ($line -replace "\u001B.*?\p{L}").Length
                $Align = $BufferWidth - $lineLength
                #Write-Debug "The buffer is $($BufferWidth) wide, and the line is $($lineLength) long so we're aligning to $($Align)"
                $result += [PoshCode.Pansies.Text]::new("&Esc;$($Align)G ")
                $RightAligned = $False
            } else {
                $line += [PoshCode.Pansies.Text]@{
                    Object          = "$ColorSeparator"
                    ForegroundColor = $LastBackground
                    BackgroundColor = $Host.UI.RawUI.BackgroundColor
                }
            }
            $result += $line + "`n"
            $line = ""
            $ColorSeparator = "&ColorSeparator;"
            $Separator = "&Separator;"
            $LastBackground = $null
        } elseif(![string]::IsNullOrWhiteSpace($string)) {
            ## If the output is just color sequences, toss it
            if(($String -replace "\u001B.*?\p{L}").Length -eq 0) {
                #Write-Debug "Skip empty output, staying $LastBackground"
                continue
            }
            if($LastBackground -or $RightAligned) {
                $line += if($block.BackgroundColor -ne $LastBackground) {
                    [PoshCode.Pansies.Text]@{
                        Object          = $ColorSeparator
                        ForegroundColor = ($LastBackground, $block.BackgroundColor)[$RightAligned]
                        BackgroundColor = ($block.BackgroundColor, $LastBackground)[$RightAligned]
                    }
                } else {
                    [PoshCode.Pansies.Text]@{
                        Object          = $Separator
                        BackgroundColor = $block.BackgroundColor
                        ForegroundColor = $block.ForegroundColor
                    }
                }
            }
            $line += $string
            $LastBackground = $block.BackgroundColor
            #Write-Debug "Normal output ($($string -replace "\u001B.*?\p{L}")) ($($($string -replace "\u001B.*?\p{L}").Length)) on $LastBackground"
        }
    }
    # At the end, output everything as one single string
    $result + $line + ([PoshCode.Pansies.Text]@{
        Object          = "$ColorSeparator&Clear;"
        ForegroundColor = $LastBackground
        BackgroundColor = $Host.UI.RawUI.BackgroundColor
    })
}
function Add-PowerLineBlock {
    <#
        .Synopsis
            Insert text or a ScriptBlock into the $Prompt
        .Description
            This function exists primarily to ensure that modules are able to modify the prompt easily without repeating themselves.
        .Example
            Add-PowerLineBlock { "`nI &hearts; PS" }
 
            Adds the classic "I ♥ PS" to your prompt on a new line. We actually recommend having a simple line in pure 16-color mode on the last line of your prompt, to ensures that PSReadLine won't mess up your colors. PSReadline overwrites your prompt line when you type -- and it can only handle 16 color mode.
        .Example
            Add-PowerLineBlock {
                New-PromptText { Get-Elapsed } -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow
            } -Index -2
 
            # This example uses Add-PowerLineBlock to insert a block into the prommpt _before_ the last block
            # It calls Get-Elapsed to show the duration of the last command as the text of the block
            # It uses New-PromptText to control the color so that it's highlighted in red if there is an error, but otherwise in dark blue (or yellow if it's an elevated host).
    #>

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

        # The position to insert the InputObject at, Defaults to -1 (to append at the end).
        [int]$Index = -1,

        [Switch]$AutoRemove,

        # If set, adds the input to the prompt without checking if it's already there
        [Switch]$Force
    )
    process {
        Write-Debug "Add-PowerLineBlock $InputObject"
        if(!$PSBoundParameters.ContainsKey("Index")) {
            $Index = $Script:PowerLineConfig.DefaultAddIndex++
        }


        $Skip = @($Global:Prompt).ForEach{$_.ToString().Trim()} -eq $InputObject.ToString().Trim()

        if($Force -or !$Skip) {
            if($Index -eq -1 -or $Index -gt $Global:Prompt.Count) {
                Write-Verbose "Appending '$InputObject' to the end of the prompt"
                $Global:Prompt.Add($InputObject)
            } elseif($Index -lt 0) {
                $Index = $Global:Prompt.Count - $Index
                Write-Verbose "Inserting '$InputObject' at $Index of the prompt"
                $Global:Prompt.Insert($Index, $InputObject)
            } else {
                Write-Verbose "Inserting '$InputObject' at $Index of the prompt"
                $Global:Prompt.Insert($Index, $InputObject)
            }
        } else {
            Write-Verbose "Prompt already contained the InputObject block"
        }

        if($AutoRemove) {
            if(($CallStack = Get-PSCallStack).Count -ge 2) {
                if($Module = $CallStack[1].InvocationInfo.MyCommand.Module) {
                    $Module.OnRemove = { Remove-PowerLineBlock $InputObject }.GetNewClosure()
                }
            }
        }
    }
}
function Export-PowerLinePrompt {
    [CmdletBinding()]
    param()

    $Local:Configuration = $Script:PowerLineConfig
    $Configuration.Prompt = [ScriptBlock[]]$global:Prompt
    $Configuration.Colors = [PoshCode.Pansies.RgbColor[]]$global:Prompt.Colors


    @{
        ExtendedCharacters = [PoshCode.Pansies.Entities]::ExtendedCharacters
        EscapeSequences    = [PoshCode.Pansies.Entities]::EscapeSequences
        PowerLineConfig    = $Script:PowerLineConfig
    } | Export-Configuration -AsHashtable

}
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
        [PoshCode.Pansies.RgbColor]$ForegroundColor,

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

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

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

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

        # The background color to use when the last command failed
        [PoshCode.Pansies.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
            }
        }
    }
    [PoshCode.Pansies.Text[]]$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
}
function New-PromptText {
    <#
        .Synopsis
            Create PoshCode.Pansies.Text 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-PromptText { 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")]
    [Alias("New-PowerLineBlock")]
    [Alias("New-TextFactory")]
    param(
        # The text, object, or scriptblock to show as output
        [Alias("Text", "Object")]
        [AllowNull()][EmptyStringAsNull()]
        [Parameter(Position=0, ValueFromPipeline, ValueFromPipelineByPropertyName)] # , Mandatory=$true
        $InputObject,

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

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

        # The foreground color to use when the process is elevated (running as administrator)
        [Alias("AFg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ElevatedForegroundColor,

        # The background color to use when the process is elevated (running as administrator)
        [Alias("ABg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ElevatedBackgroundColor,

        # The foreground color to use when the last command failed
        [Alias("EFg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ErrorForegroundColor,

        # The background color to use when the last command failed
        [Alias("EBg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ErrorBackgroundColor
    )
    process {

        $output = [PoshCode.Pansies.Text]@{
            Object = $InputObject
        }
        # Always set the defaults first, if they're provided
        if($PSBoundParameters.ContainsKey("ForegroundColor") -and $ForegroundColor -ne $Null) {
            $output.ForegroundColor = $ForegroundColor
        }
        if($PSBoundParameters.ContainsKey("BackgroundColor") -and $BackgroundColor -ne $Null) {
            $output.BackgroundColor = $BackgroundColor
        }

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

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

        $output
    }
}
function Remove-PowerLineBlock {
    <#
        .Synopsis
            Remove text or a ScriptBlock from the $Prompt
        .Description
            This function exists primarily to ensure that modules are able to clean up the prompt easily when they're removed
        .Example
            Remove-PowerLineBlock {
                New-PromptText { Get-Elapsed } -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow
            }
 
            Removes the specified block. Note that it must be _exactly_ the same as when you added it.
    #>

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

        $Index = @($Global:Prompt).ForEach{$_.ToString().Trim()}.IndexOf($InputObject.ToString().Trim())
        if($Index -ge 0) {
            $null = $Global:Prompt.RemoveAt($Index)
        }
        if($Index -lt $Script:PowerLineConfig.DefaultAddIndex) {
            $Script:PowerLineConfig.DefaultAddIndex--
        }
    }
}
function Set-PowerLinePrompt {
    #.Synopsis
    # Set the default PowerLine prompt function which uses the $Prompt variable
    #.Description
    # Overwrites the current prompt function with one that uses the $Prompt 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 -FullColor
    #
    # Sets the powerline prompt and forces the assumption of full RGB color support instead of 16 color
    [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
        [Alias("CurrentDirectory")]
        [switch]$SetCurrentDirectory,

        # 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, assume full color support, otherwise normalize to 16 ConsoleColor
        [Parameter()]
        [switch]$FullColor,

        # 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,

        # Add a "I ♥ PS" on a line by itself to it's prompt (using ConsoleColors, to keep it safe from PSReadLine)
        [switch]$Newline,

        # Add a right-aligned timestamp before the newline (implies Newline)
        [switch]$Timestamp,

        # One or more scriptblocks you want to use as your new prompt
        [System.Collections.Generic.List[ScriptBlock]]$Prompt,

        # One or more colors you want to use as the prompt background
        [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$Colors,

        # If set, calls Export-PowerLinePrompt
        [Switch]$Save

    )
    if ($null -eq $script:OldPrompt) {
        $script:OldPrompt = $function:global:prompt
        $MyInvocation.MyCommand.Module.OnRemove = {
            $function:global:prompt = $script:OldPrompt
        }
    }

    # Hide these from serialization
    $null = $PSBoundParameters.Remove("Save")
    $null = $PSBoundParameters.Remove("Newline")
    $null = $PSBoundParameters.Remove("Timestamp")

    $Configuration = Import-Configuration

    # Upodate the saved PowerLinePrompt with the parameters
    if(!$Configuration.PowerLineConfig) {
        $Configuration.PowerLineConfig = @{}
    }
    $PowerLineConfig = $Configuration.PowerLineConfig | Update-Object $PSBoundParameters

    if($Configuration.ExtendedCharacters) {
        foreach($key in $Configuration.ExtendedCharacters.Keys) {
            [PoshCode.Pansies.Entities]::ExtendedCharacters.$key = $Configuration.ExtendedCharacters.$key
        }
    }

    if($Configuration.EscapeSequences) {
        foreach($key in $Configuration.EscapeSequences.Keys) {
            [PoshCode.Pansies.Entities]::EscapeSequences.$key = $Configuration.EscapeSequences.$key
        }
    }

    if ($PowerLineConfig.FullColor -eq $Null -and $Host.UI.SupportsVirtualTerminal) {
        $PowerLineConfig.FullColor = (Get-Process -Id $global:Pid).MainWindowHandle -ne 0
    }

    # For Prompt and Colors we want to support modifying the global variable outside this function
    Write-Warning "Before Prompt Count: $($global:Prompt.Count) and $($Local:Prompt.Count)"
    if($PSBoundParameters.ContainsKey("Prompt")) {
        Write-Warning "Set Prompt"
        [System.Collections.Generic.List[ScriptBlock]]$global:Prompt = $Local:Prompt

    } elseif($global:Prompt.Count -eq 0 -and $PowerLineConfig.Prompt.Count -gt 0) {
        Write-Warning "ReSet Prompt"
        [System.Collections.Generic.List[ScriptBlock]]$global:Prompt = [ScriptBlock[]]@($PowerLineConfig.Prompt)

    } elseif($global:Prompt.Count -eq 0) {
        Write-Warning "Initialize Prompt"
        [ScriptBlock[]]$PowerLineConfig.Prompt = { $MyInvocation.HistoryId }, { Get-SegmentedPath }
        [System.Collections.Generic.List[ScriptBlock]]$global:Prompt = $PowerLineConfig.Prompt
    }

    # Prefer the existing colors over the saved colors, but not over the colors parameter
    Write-Warning "Before InitializeColor Count: $($global:Prompt.Count)"
    if($PSBoundParameters.ContainsKey("Colors")) {
        InitializeColor $Colors
    } elseif($global:Prompt.Colors) {
        InitializeColor $global:Prompt.Colors
    } elseif($PowerLineConfig.Colors) {
        InitializeColor $PowerLineConfig.Colors
    } else {
        InitializeColor
    }
    Write-Warning "After InitializeColor Count: $($global:Prompt.Count)"

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

    if($null -eq $PowerLineConfig.DefaultAddIndex) {
        $PowerLineConfig.DefaultAddIndex    = -1
    }

    $Script:PowerLineConfig = $PowerLineConfig

    if($Newline -or $Timestamp) {
        $Script:PowerLineConfig.DefaultAddIndex = $Insert = $global:Prompt.Count

        @(
            if($Timestamp) {
                { "`t" }
                { Get-Elapsed }
                { Get-Date -f "T" }
            }
            { "`n" }
            { New-PromptText { "I $(New-PromptText -Fg Red -EFg White "&hearts;$([char]27)[30m") PS" } -Bg White -EBg Red -Fg Black }
        ) | Add-PowerLineBlock

        $Script:PowerLineConfig.DefaultAddIndex = $Insert
    } else {
        $Script:PowerLineConfig.DefaultAddIndex = -1
    }

    # Finally, update the prompt function
    $function:global:prompt = $function:script:Prompt
    [PoshCode.Pansies.RgbColor]::ResetConsolePalette()

    # If they asked us to save, or if there's nothing saved yet
    if($Save -or ($PSBoundParameters.Count -and !(Test-Path (Join-Path (Get-StoragePath) Configuration.psd1)))) {
        Export-PowerLinePrompt
    }
}

Set-PowerLinePrompt
function Test-Elevation {
    <#
    .Synopsis
        Get a value indicating whether the process is elevated (running as administrator)
    #>

    [CmdletBinding()]
    param()

    [Security.Principal.WindowsIdentity]::GetCurrent().Owner.IsWellKnown("BuiltInAdministratorsSid")
}
function Test-Success {
    <#
    .Synopsis
        Get a value indicating whether the last command succeeded or not
    #>

    [CmdletBinding()]
    param()

    $script:LastSuccess
}

Export-ModuleMember -Function *-* -Alias *