-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogging.psm1
More file actions
1404 lines (1135 loc) · 46.7 KB
/
Logging.psm1
File metadata and controls
1404 lines (1135 loc) · 46.7 KB
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Using module .\PSStyle.psm1;
Using module @{
ModuleName = 'PSReadLine';
ModuleVersion = '2.3.2';
}
<#
.SYNOPSIS
Writes a message to the console or returns it, based on provided parameters.
.DESCRIPTION
This function processes a message with optional colour, prefix, and pass-through behavior.
If PassThru is specified, the function returns the message instead of writing it to the console.
.PARAMETER InputObject
A hashtable of parameters to be splatted into Invoke-Write. When passed, all other parameters are ignored.
.PARAMETER PSMessage
Specifies the message to be logged.
.PARAMETER PSPrefix
An optional Unicode prefix (e.g., emoji) to prepend to the output if Unicode is supported.
.PARAMETER PSColour
Specifies the color of the message text if colour output is supported.
.PARAMETER MultiLineIndent
Sets the number of characters to indent multiline message lines.
.PARAMETER ShouldWrite
Indicates whether the function should write the message to the console.
.PARAMETER PassThru
When set, returns the formatted message instead of writing it to the console.
.EXAMPLE
```powershell
Invoke-Write -PSMessage "Hello World" -PSColour "Cyan" -ShouldWrite $True
```
.EXAMPLE
```powershell
Invoke-Write @{ PSMessage = "Hello World"; PSColour = "Green"; PassThru = $true; ShouldWrite = $True }
```
#>
function Invoke-Write {
[CmdletBinding(PositionalBinding, DefaultParameterSetName = 'Splat')]
param (
[Parameter(ParameterSetName = 'InputObject', Position = 0, ValueFromPipeline)]
[HashTable]$InputObject,
[Parameter(ParameterSetName = 'Splat', Mandatory, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[String]$PSMessage,
[Parameter(ParameterSetName = 'Splat', ValueFromPipelineByPropertyName)]
[String]$PSPrefix,
[Parameter(ParameterSetName = 'Splat', Mandatory, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[String]$PSColour,
[Parameter(ParameterSetName = 'Splat', ValueFromPipelineByPropertyName)]
[Int]$MultiLineIndent = 0,
[Parameter(ParameterSetName = 'Splat', ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Boolean]$ShouldWrite,
[Parameter(ParameterSetName = 'Splat', ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Switch]$PassThru
)
process {
if ($InputObject) {
Invoke-Write @InputObject;
return;
}
if ($PSBoundParameters.ContainsKey('ShouldWrite') -and (-not $ShouldWrite)) {
return;
}
[String]$Local:NewLineTab = if ($PSPrefix -and (Test-SupportsUnicode)) {
"$(' ' * $(($PSPrefix.Length + $MultiLineIndent)))";
} else { (' ' * $MultiLineIndent); }
[String]$Local:FormattedMessage = if ($PSMessage.Contains("`n")) {
$PSMessage -replace "`n", "`n$Local:NewLineTab+ ";
} else { $PSMessage; }
if (Test-SupportsColour) {
$ColourSeq = [PSStyle]::MapForegroundColorToEscapeSequence($PSColour);
# If the string contains any instances of PSStyle.Reset we need to add the colour sequence before after it.
$Local:FormattedMessage = $Local:FormattedMessage -replace ([Regex]::Escape($PSStyle.Reset)), "$($PSStyle.Reset)$ColourSeq";
$Local:FormattedMessage = "$ColourSeq$Local:FormattedMessage$($PSStyle.Reset)";
}
[String]$Local:FormattedMessage = if ($PSPrefix -and (Test-SupportsUnicode)) {
"$PSPrefix $Local:FormattedMessage";
} else { $Local:FormattedMessage; }
if ($PassThru) {
return $Local:FormattedMessage;
} else {
$InformationPreference = 'Continue';
Write-Information $Local:FormattedMessage;
}
}
}
function Format-Error(
[Parameter(Mandatory, HelpMessage = 'The error records invocation info.', ParameterSetName = 'InvocationInfo')]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.InvocationInfo]$InvocationInfo,
[Parameter(Mandatory, HelpMessage = 'The error record to format.', ParameterSetName = 'ErrorRecord')]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Language.ParseError]$ErrorRecord,
[Parameter(HelpMessage = 'The Unicode Prefix to use if the terminal supports Unicode.')]
[AllowNull()]
[String]$Message,
[Parameter(HelpMessage = 'The Unicode Prefix to use if the terminal supports Unicode.')]
[ValidateNotNullOrEmpty()]
[Alias('Prefix')]
[String]$UnicodePrefix,
[Parameter(HelpMessage = 'Return the formatted message instead of writing it to the console.')]
[Switch]$PassThru,
[Int]$PreviewExtraLines = 5
) {
$Rows = [ordered]@{
File = @{
Value = $null;
}
Where = @{
Value = $null
}
Preview = @{
Value = $null;
Statement = $null;
StatementLine = 0;
}
}
$Padding = ($Rows.GetEnumerator() | ForEach-Object {
if ($null -eq $_.Value.Name) {
$_.Value.Name = $_.Key;
}
$_.Value.Name.Length;
} | Measure-Object -Maximum | Select-Object -ExpandProperty Maximum) + 1;
if ($PSCmdlet.ParameterSetName -eq 'InvocationInfo') {
$Line = $InvocationInfo.Line | ForEach-Object { $_.Trim() };
if ($InvocationInfo.ScriptName) { $Rows.File.Value = (Format-TrimToConsoleWidth -Line $InvocationInfo.ScriptName -TrimType Left -Padding $Padding).String; }
if ($InvocationInfo.Statement) {
$Statement = $InvocationInfo.Statement;
# FIXME - Don't do it this way
$StatementIndex = $Line.IndexOf($Statement);
# FIXME: This is a hack to fix the issue where the statement index is -1, this shouldn't happen!
if ($StatementIndex -lt 0) {
$StatementIndex = 0;
}
} else {
$StatementIndex = 0;
$Statement = $Line;
}
$Padding = $Padding # + ($EllipsisLength * 2);
$ConsoleWidth = $Host.UI.RawUI.BufferSize.Width - $Padding;
$FileStream = [System.IO.File]::OpenRead($InvocationInfo.ScriptName);
[System.IO.StreamReader]$StreamReader = [System.IO.StreamReader]::new($FileStream);
# TODO - Don't have to read the whole file to find this.
$Content = $StreamReader.ReadToEnd();
$StatementIndex = $Content.IndexOf($Statement);
$Result = Get-SurroundingContext `
-Statement $Statement `
-StreamReader $StreamReader `
-FocusRange ([Tuple]::Create($StatementIndex, ($StatementIndex + $Statement.Length))) `
-MaxLineLength $ConsoleWidth;
$String = [String]::new($Result.Buffer);
$StreamReader.Close();
$FileStream.Close();
$Position = Get-Position -String $String -Search $Statement;
$Rows.Preview.StatementIndex = $Position.Start;
$Rows.Preview.StatementLine = $Position.StartLine;
$Rows.Preview.Statement = $Statement;
$Rows.Preview.Value = (Format-ColourAt `
-String $String `
-StartIndex $Rows.Preview.StatementIndex `
-EndIndex ($Rows.Preview.StatementIndex + $Rows.Preview.Statement.Length) `
-ColourSequence $PSStyle.Foreground.Red);
$Rows.Where.Value = Format-WherePosition `
-StartLine $InvocationInfo.ScriptLineNumber `
-StartColumn $InvocationInfo.OffsetInLine `
-EndLine ($InvocationInfo.ScriptLineNumber + $Position.EndLine) `
-EndColumn $Position.EndColumn;
} else {
$Message = $ErrorRecord.Message;
$Rows.File.Value = (Format-TrimToConsoleWidth -Line $ErrorRecord.Extent.File -TrimType Left -Padding $Padding).String;
$Rows.Where.Value = Format-WherePosition `
-StartLine $ErrorRecord.Extent.StartLineNumber `
-EndLine $ErrorRecord.Extent.EndLineNumber `
-StartColumn $ErrorRecord.Extent.StartColumnNumber `
-EndColumn $ErrorRecord.Extent.EndColumnNumber;
$Statement = $ErrorRecord.Extent.Text;
$Colour = $PSStyle.Foreground.Red;
$Reset = $PSStyle.Reset;
$ConsoleWidth = $Host.UI.RawUI.BufferSize.Width - $Padding;
$StatementLength = $Statement.Length;
$ContextFromEachSide = [Math]::Floor(($Local:ConsoleWidth - $Statement.Length) / 2);
if ($ErrorRecord.Extent.File -and $ContextFromEachSide -gt 0) {
$FileStream = [System.IO.File]::OpenRead($ErrorRecord.Extent.File);
[System.IO.StreamReader]$StreamReader = [System.IO.StreamReader]::new($FileStream);
$Buffer = New-Object char[] (($Local:ConsoleWidth * ($PreviewExtraLines * 2)) + $Colour.Length + $Reset.Length);
$StartOffset = $ErrorRecord.Extent.StartOffset;
$Backwards = Get-WalkedBuffer `
-StreamReader $StreamReader `
-StartOffset $StartOffset `
-Direction Backward `
-MaxLineLength $Local:ConsoleWidth `
-MaxLines ([Math]::Ceiling($PreviewExtraLines / 2));
$Rows.Preview.StatementLine = $Backwards.LinesAdded;
$Offset = $Backwards.Buffer.Length;
for ($i = 0; $i -lt $Backwards.Buffer.Length; $i++) {
$Buffer[$i] = $Backwards.Buffer[$i];
}
for ($i = 0; $i -lt $Colour.Length; $i++) { $Buffer[$Local:Offset + $i] = $Colour[$i]; }
$StatementLength += $Colour.Length;
$StatementIndex = $Offset
for ($i = $StatementIndex; $i -le $StatementIndex + $Statement.Length; $i++) {
$BufferIndex = $i + $Colour.Length;
$TempBufferIndex = $i - $Offset;
$Buffer[$BufferIndex] = $Statement[$TempBufferIndex];
}
for ($i = 0; $i -lt $Reset.Length; $i++) { $Buffer[$Local:StatementIndex + $Local:StatementLength + $i] = $Reset[$i]; }
$StatementLength += $Reset.Length;
$Forward = Get-WalkedBuffer `
-StreamReader $StreamReader `
-StartOffset ($StartOffset + $Statement.Length) `
-Direction Forward `
-MaxLineLength $Local:ConsoleWidth `
-MaxLines ([Math]::Floor($PreviewExtraLines / 2));
for ($i = 0; $i -lt $Forward.Buffer.Length; $i++) {
$Buffer[$StatementIndex + $StatementLength + $i] = $Forward.Buffer[$i];
}
$StreamReader.Close();
$FileStream.Close();
$FormatResult = Format-TrimKeepingMultilineIndent -String ([String]::new($Buffer));
$Rows.Preview.Value = $FormatResult.String;
$Rows.Preview.Statement = $Statement;
$Rows.Preview.StatementIndex = $ErrorRecord.Extent.StartColumnNumber - 1 - $FormatResult.Indent;
} else {
$StatementIndex = 0;
$Rows.Preview.Value = $Statement;
}
}
[System.Collections.Generic.List[String]]$PreviewLines = ($Rows.Preview.Value -split "`n") | Where-Object { -not [String]::IsNullOrWhiteSpace($_) };
$Highlight = Format-ColourAndReset (
(' ' * ($Rows.Preview.StatementIndex)) +
('^' * [Math]::Max(1, [Math]::Min($Rows.Preview.Statement.Length, $ConsoleWidth - $Rows.Preview.StatementIndex - 2)))
) $PSStyle.Foreground.Red;
if (-not [String]::IsNullOrWhiteSpace($Message)) {
$Message = Format-ColourAndReset ((' ' * $Rows.Preview.StatementIndex) + $Message) $PSStyle.Foreground.Red;
$Message = $Message -replace "\. ", "`n"; # FIXME - Seems to be ok to split messages by sentances but needs a more robust implementation.
}
$LineOffset = $Rows.Preview.StatementLine;
if ($Rows.Preview.StatementLine -eq ($PreviewLines.Count - 1)) {
$PreviewLines += $Highlight;
if ($Message) { $PreviewLines += $Message; }
} else {
Invoke-Info "Inserting Highlight at $LineOffset in $($PreviewLines.Count) lines.";
$PreviewLines.Insert($LineOffset, $Highlight);
if ($Message) { $PreviewLines.Insert($LineOffset + 1, $Message); }
}
$Rows.Preview.Value = $PreviewLines -join "`n";
# Fucking PS 5 doesn't allow variable overrides so i have to add the colour to all of them. :<(
[HashTable]$Private:BaseArgs = @{
PSPrefix = if ($UnicodePrefix) { $UnicodePrefix } else { $null };
ShouldWrite = $True;
PassThru = $PassThru;
MultiLineIndent = $Padding;
};
if (-not $Rows.File.Value) { $Rows.File.Value = 'Unknown'; }
$Rows.File.Value = Format-ColourAndReset $Rows.File.Value $PSStyle.Foreground.Red;
$Rows.Where.Value = Format-ColourAndReset $Rows.Where.Value $PSStyle.Foreground.Red;
$Rows.Keys | ForEach-Object {
$Value = $Rows[$_].Value;
$Row = $Rows[$_].Name;
if ($null -eq $Value -or [String]::IsNullOrEmpty($Value)) {
Invoke-Debug "Skipping row $Row as it has no value.";
return;
}
$Prefix = Format-ColourAndReset "$Row$(' ' * ($Padding - $Row.Length))|" $PSStyle.Foreground.Cyan;
Invoke-Write @Private:BaseArgs -PSMessage "$Prefix $Value" -PSColour White;
}
}
#region Logging at Level Functions
<#
.SYNOPSIS
Writes a message to the console at the Verbose level if the VerbosePreference is not SilentlyContinue or Ignore.
.PARAMETER InputObject
A hashtable of parameters to be splatted into Invoke-Verbose. When passed, all other parameters are ignored.
.PARAMETER Message
The message to write to the console.
.PARAMETER UnicodePrefix
The Unicode Prefix to use if the terminal supports Unicode.
.PARAMETER PassThru
Return the formatted message instead of writing it to the console.
#>
function Invoke-Verbose {
[CmdletBinding(PositionalBinding, DefaultParameterSetName = 'Splat')]
param(
[Parameter(ParameterSetName = 'InputObject', Position = 0, ValueFromPipeline)]
[HashTable]$InputObject,
[Parameter(ParameterSetName = 'Splat', Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Message,
[Parameter(ParameterSetName = 'Splat', Position = 1, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('Prefix')]
[String]$UnicodePrefix,
[Parameter(ValueFromPipelineByPropertyName)]
[Switch]$PassThru
)
process {
if ($InputObject) {
Invoke-Verbose @InputObject;
return;
}
$Local:Params = @{
PSPrefix = if ($UnicodePrefix) { $UnicodePrefix } else { '🔍' };
PSMessage = $Message;
PSColour = 'Yellow';
ShouldWrite = $PSCmdlet.GetVariableValue('VerbosePreference') -notmatch 'SilentlyContinue|Ignore';
PassThru = $PassThru;
};
Invoke-Write @Local:Params;
}
}
<#
.SYNOPSIS
Writes a message to the console at the Debug level if the DebugPreference is not SilentlyContinue or Ignore.
.PARAMETER InputObject
A hashtable of parameters to be splatted into Invoke-Debug. When passed, all other parameters are ignored.
.PARAMETER Message
The message to write to the console.
.PARAMETER UnicodePrefix
The Unicode Prefix to use if the terminal supports Unicode.
.PARAMETER PassThru
Return the formatted message instead of writing it to the console.
#>
function Invoke-Debug {
[CmdletBinding(PositionalBinding, DefaultParameterSetName = 'Splat')]
param(
[Parameter(ParameterSetName = 'InputObject', Position = 0, ValueFromPipeline)]
[HashTable]$InputObject,
[Parameter(ParameterSetName = 'Splat', Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Message,
[Parameter(ParameterSetName = 'Splat', Position = 1, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('Prefix')]
[String]$UnicodePrefix,
[Parameter(ValueFromPipelineByPropertyName)]
[Switch]$PassThru
)
process {
if ($InputObject) {
Invoke-Debug @InputObject;
return;
}
$Local:Params = @{
PSPrefix = if ($UnicodePrefix) { $UnicodePrefix } else { '🐛' };
PSMessage = $Message;
PSColour = 'Magenta';
ShouldWrite = $PSCmdlet.GetVariableValue('DebugPreference') -notmatch 'SilentlyContinue|Ignore';
PassThru = $PassThru;
};
Invoke-Write @Local:Params;
}
}
<#
.SYNOPSIS
Writes a message to the console at the Information level if the InformationPreference is not Ignore.
.PARAMETER InputObject
A hashtable of parameters to be splatted into Invoke-Info. When passed, all other parameters are ignored.
.PARAMETER Message
The message to write to the console.
.PARAMETER UnicodePrefix
The Unicode Prefix to use if the terminal supports Unicode.
.PARAMETER PassThru
Return the formatted message instead of writing it to the console.
#>
function Invoke-Info {
[CmdletBinding(PositionalBinding, DefaultParameterSetName = 'Splat')]
param(
[Parameter(ParameterSetName = 'InputObject', Position = 0, ValueFromPipeline)]
[HashTable]$InputObject,
[Parameter(ParameterSetName = 'Splat', Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Message,
[Parameter(ParameterSetName = 'Splat', Position = 1, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('Prefix')]
[String]$UnicodePrefix,
[Parameter(ValueFromPipelineByPropertyName)]
[Switch]$PassThru
)
process {
if ($InputObject) {
Invoke-Info @InputObject;
return;
}
$Local:Params = @{
PSPrefix = if ($UnicodePrefix) { $UnicodePrefix } else { 'ℹ️' };
PSMessage = $Message;
PSColour = 'Cyan';
ShouldWrite = $PSCmdlet.GetVariableValue('InformationPreference') -ne 'Ignore'
PassThru = $PassThru;
};
Invoke-Write @Local:Params;
}
}
<#
.SYNOPSIS
Writes a message to the console at the Warning level if the WarningPreference is not SilentlyContinue or Ignore.
.PARAMETER InputObject
A hashtable of parameters to be splatted into Invoke-Warn. When passed, all other parameters are ignored.
.PARAMETER Message
The message to write to the console.
.PARAMETER UnicodePrefix
The Unicode Prefix to use if the terminal supports Unicode.
.PARAMETER PassThru
Return the formatted message instead of writing it to the console.
#>
function Invoke-Warn {
[CmdletBinding(PositionalBinding, DefaultParameterSetName = 'Splat')]
param(
[Parameter(ParameterSetName = 'InputObject', Position = 0, ValueFromPipeline)]
[HashTable]$InputObject,
[Parameter(ParameterSetName = 'Splat', Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Message,
[Parameter(ParameterSetName = 'Splat', Position = 1, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('Prefix')]
[String]$UnicodePrefix,
[Parameter(ValueFromPipelineByPropertyName)]
[Switch]$PassThru
)
process {
if ($InputObject) {
Invoke-Warn @InputObject;
return;
}
$Local:Params = @{
PSPrefix = if ($UnicodePrefix) { $UnicodePrefix } else { '⚠️' };
PSMessage = $Message;
PSColour = 'Yellow';
ShouldWrite = $PSCmdlet.GetVariableValue('WarningPreference') -notmatch 'SilentlyContinue|Ignore';
PassThru = $PassThru;
};
Invoke-Write @Local:Params;
}
}
<#
.SYNOPSIS
Writes a message to the console at the Error level if the ErrorPreference is not SilentlyContinue or Ignore.
.PARAMETER InputObject
A hashtable of parameters to be splatted into Invoke-Error. When passed, all other parameters are ignored.
.PARAMETER Message
The message to write to the console.
.PARAMETER UnicodePrefix
The Unicode Prefix to use if the terminal supports Unicode.
.PARAMETER PassThru
Return the formatted message instead of writing it to the console.
.PARAMETER Throw
If this is a terminating error and should be thrown.
.PARAMETER ErrorCategory
The error category to use when throwing an error.
#>
function Invoke-Error {
[CmdletBinding(PositionalBinding, DefaultParameterSetName = 'Splat')]
param(
[Parameter(ParameterSetName = 'InputObject', Position = 0, ValueFromPipeline)]
[HashTable]$InputObject,
[Parameter(ParameterSetName = 'Splat', Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Message,
[Parameter(ParameterSetName = 'Splat', Position = 1, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('Prefix')]
[String]$UnicodePrefix,
[Parameter(ValueFromPipelineByPropertyName)]
[Switch]$PassThru,
[Parameter(ValueFromPipelineByPropertyName)]
[Switch]$Throw,
[Parameter(ValueFromPipelineByPropertyName)]
[System.Management.Automation.ErrorCategory]$ErrorCategory = [System.Management.Automation.ErrorCategory]::NotSpecified,
[Parameter(DontShow, ValueFromPipelineByPropertyName)]
[System.Management.Automation.InvocationInfo]$Caller = (Get-PSCallStack)[0].InvocationInfo,
[Parameter(DontShow, ValueFromPipelineByPropertyName)]
[System.Management.Automation.PSCmdlet]$CallerCmdlet = $PSCmdlet
)
process {
if ($InputObject) {
Invoke-Error @InputObject;
return;
}
if (-not $Throw) {
$Local:Params = @{
PSPrefix = if ($UnicodePrefix) { $UnicodePrefix } else { '❌' };
PSMessage = $Message;
PSColour = 'Red';
ShouldWrite = $PSCmdlet.GetVariableValue('ErrorActionPreference') -notmatch 'SilentlyContinue|Ignore';
PassThru = $PassThru;
};
Invoke-Write @Local:Params;
}
if ($Throw) {
$ErrorRecord = [System.Management.Automation.ErrorRecord]::new(
[System.Exception]::new($Message),
'Error',
$ErrorCategory,
$Caller
);
$Cmdlet = if ($CallerCmdlet) { $CallerCmdlet } else { $PSCmdlet; }
$Cmdlet.ThrowTerminatingError($ErrorRecord);
}
}
}
#endregion
<#
.SYNOPSIS
Invokes a ScriptBlock with a timeout, optionally allowing the user to cancel the timeout.
.PARAMETER Timeout
The timeout in milliseconds.
.PARAMETER Activity
The message to write to the console.
.PARAMETER StatusMessage
The format string to use when writing the status message, must contain a single placeholder for the time left in seconds.
.PARAMETER TimeoutScript
The ScriptBlock to invoke if timeout is reached and wasn't cancelled.
.PARAMETER CancelScript
The ScriptBlock to invoke if timeout was cancelled.
.PARAMETER AllowCancel
If the timeout is cancellable.
#>
function Invoke-Timeout {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[Int]$Timeout,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Activity,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$StatusMessage,
[Parameter()]
[ScriptBlock]$TimeoutScript,
[Parameter(ParameterSetName = 'Cancellable')]
[ScriptBlock]$CancelScript,
[Parameter(ParameterSetName = 'Cancellable')]
[Switch]$AllowCancel
)
process {
# Ensure that the input buffer is flushed, otherwise the user can press escape before the loop starts and it would cancel it.
$Host.UI.RawUI.FlushInputBuffer();
[String]$Local:Prefix = if ($AllowCancel) { '⏳' } else { '⏲️' };
if ($AllowCancel) {
Invoke-Info -Message "$Activity is cancellable, press any key to cancel." -UnicodePrefix $Local:Prefix;
}
[TimeSpan]$Local:TimeInterval = [TimeSpan]::FromMilliseconds(50);
[TimeSpan]$Local:TimeLeft = [TimeSpan]::FromSeconds($Timeout);
do {
[DateTime]$Local:StartAt = Get-Date;
if ($AllowCancel -and [Console]::KeyAvailable) {
Invoke-Debug -Message 'Timeout cancelled by user.';
break;
}
Write-Progress `
-Activity $Activity `
-Status ($StatusMessage -f ([Math]::Floor($Local:TimeLeft.TotalSeconds))) `
-PercentComplete ($Local:TimeLeft.TotalMilliseconds / ($Timeout * 10)) `
-Completed:($Local:TimeLeft.TotalMilliseconds -eq 0)
[TimeSpan]$Local:ElaspedTime = (Get-Date) - $Local:StartAt;
[TimeSpan]$Local:IntervalMinusElasped = ($Local:TimeInterval - $Local:ElaspedTime);
if ($Local:IntervalMinusElasped.TotalMilliseconds -gt 0) {
$Local:TimeLeft -= $Local:IntervalMinusElasped;
# Can't use -duration because it isn't available in PS 5.1
Start-Sleep -Milliseconds $Local:IntervalMinusElasped.TotalMilliseconds;
} else {
$Local:TimeLeft -= $Local:ElaspedTime;
}
} while ($Local:TimeLeft.TotalMilliseconds -gt 0)
Invoke-Debug "Finished waiting for $Activity, time left: $Local:TimeLeft.";
if ($Local:TimeLeft -le 0) {
Invoke-Verbose -Message 'Timeout reached, invoking timeout script if one is present.' -UnicodePrefix $Local:Prefix;
if ($TimeoutScript) {
& $TimeoutScript;
}
} elseif ($AllowCancel) {
Invoke-Verbose -Message 'Timeout cancelled, invoking cancel script if one is present.' -UnicodePrefix $Local:Prefix;
if ($CancelScript) {
& $CancelScript;
}
}
Write-Progress -Activity $Activity -Completed;
}
}
<#
.SYNOPSIS
Invokes a ScriptBlock with a progress bar.
.PARAMETER Id
The ID of the progress bar, used to display multiple progress bars at once.
.PARAMETER Activity
The activity to display in the progress bar.
.PARAMETER Status
The status message to display in the progress bar.
This is formatted with three placeholders:
The current completion percentage.
The index of the item being processed.
The total number of items being processed.
.PARAMETER Get
The ScriptBlock which returns the items to process.
.PARAMETER Process
The ScriptBlock to process each item.
.PARAMETER Format
The ScriptBlock that formats the items name for the progress bar.
If left empty, the ToString method is used.
.PARAMETER FailedProcessItem
The ScriptBlock to invoke when an item fails to process.
#>
function Invoke-Progress {
Param(
[Parameter()]
[Int]$Id = 0,
[Parameter()]
[String]$Activity,
[Parameter()]
[String]$Status,
[Parameter(Mandatory)]
[ValidateNotNull()]
[ScriptBlock]$Get,
[Parameter(Mandatory)]
[ValidateNotNull()]
[ScriptBlock]$Process,
[Parameter()]
[ValidateNotNull()]
[ScriptBlock]$Format = { $_.ToString() },
[Parameter()]
[ScriptBlock]$FailedProcessItem
)
process {
if (-not $Activity) {
$Local:FuncName = (Get-PSCallStack)[1].InvocationInfo.MyCommand.Name;
$Activity = if (-not $Local:FuncName) {
'Main';
} else { $Local:FuncName; }
}
Write-Progress -Id:$Id -Activity:$Activity -CurrentOperation 'Getting items...' -PercentComplete 0;
[Object[]]$Local:InputItems = $Get.InvokeReturnAsIs();
Write-Progress -Id:$Id -Activity:$Activity -PercentComplete 1;
if ($null -eq $Local:InputItems -or $Local:InputItems.Count -eq 0) {
Write-Progress -Id:$Id -Activity:$Activity -Status 'No items found.' -PercentComplete 100 -Completed;
return;
} else {
Write-Progress -Id:$Id -Activity:$Activity -Status "Processing $($Local:InputItems.Count) items...";
}
[System.Collections.IList]$Local:FailedItems = New-Object System.Collections.Generic.List[System.Object];
[Double]$Local:PercentPerItem = 99 / $Local:InputItems.Count;
[Double]$Local:PercentComplete = 0;
[TimeSpan]$Local:TotalTime = [TimeSpan]::FromSeconds(0);
[Int]$Local:ItemsProcessed = 0;
foreach ($Item in $Local:InputItems) {
[String]$ItemName;
[TimeSpan]$Local:TimeTaken = (Measure-Command {
$ItemName = if ($Format) { $Format.InvokeReturnAsIs($Item) } else { $Item; };
});
$Local:TotalTime += $Local:TimeTaken;
$Local:ItemsProcessed++;
# Calculate the estimated time remaining
$Local:AverageTimePerItem = $Local:TotalTime / $Local:ItemsProcessed;
$Local:ItemsRemaining = $Local:InputItems.Count - $Local:ItemsProcessed;
$Local:EstimatedTimeRemaining = $Local:AverageTimePerItem * $Local:ItemsRemaining
Invoke-Debug "Items remaining: $Local:ItemsRemaining";
Invoke-Debug "Average time per item: $Local:AverageTimePerItem";
Invoke-Debug "Estimated time remaining: $Local:EstimatedTimeRemaining";
$Local:Params = @{
Id = $Id;
Activity = $Activity;
CurrentOperation = "Processing [$ItemName]...";
SecondsRemaining = $Local:EstimatedTimeRemaining.TotalSeconds;
PercentComplete = [Math]::Ceiling($Local:PercentComplete);
};
if ($Status) {
$Local:Params.Status = ($Status -f @($Local:PercentComplete, ($Local:InputItems.IndexOf($Item) + 1), $Local:InputItems.Count));
}
Write-Progress @Local:Params;
try {
$ErrorActionPreference = 'Stop';
$Process.InvokeReturnAsIs($Item);
} catch {
Invoke-Warn "Failed to process item [$ItemName]";
Invoke-Debug -Message "Due to reason - $($_.Exception.Message)";
try {
$ErrorActionPreference = 'Stop';
if ($null -eq $FailedProcessItem) {
$Local:FailedItems.Add($Item);
} else { $FailedProcessItem.InvokeReturnAsIs($Item); }
} catch {
Invoke-Warn "Failed to process item [$ItemName] in failed process item block";
}
}
$Local:PercentComplete += $Local:PercentPerItem;
}
Write-Progress -Id:$Id -Activity:$Activity -PercentComplete 100 -Completed;
if ($Local:FailedItems.Count -gt 0) {
Invoke-Warn "Failed to process $($Local:FailedItems.Count) items";
Invoke-Warn "Failed items: `n`t$($Local:FailedItems -join "`n`t")";
}
}
}
#region Utility Functions
function Format-ColourAndReset {
[CmdletBinding()]
[OutputType([String])]
param(
[Parameter(Mandatory)]
[String]$String,
[Parameter(Mandatory)]
[String]$ColourSequence
)
if ([String]::IsNullOrEmpty($String)) {
return $null;
}
return "$ColourSequence$String$($PSStyle.Reset)";
}
function Format-ColourAt {
[CmdletBinding()]
[OutputType([String])]
param(
[Parameter(Mandatory)]
[String]$String,
[Parameter(Mandatory)]
[Int]$StartIndex,
[Parameter(Mandatory)]
[Int]$EndIndex,
[Parameter(Mandatory)]
[String]$ColourSequence
)
if ([String]::IsNullOrEmpty($String)) {
return $null;
}
try {
$ThrowArgs = @{
Throw = $True;
ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument;
Caller = $PSCmdlet.MyInvocation;
CallerCmdlet = $PSCmdlet;
}
if ($StartIndex -lt 0) { Invoke-Error 'StartIndex cannot be less than 0.' @ThrowArgs; }
if ($EndIndex -gt $String.Length) { Invoke-Error "EndIndex{$EndIndex} cannot be greater than the length{$($String.Length)} of the string." @ThrowArgs; }
if ($StartIndex -gt $EndIndex) { Invoke-Error 'StartIndex cannot be greater than EndIndex.' @ThrowArgs; }
} catch {
$PSCmdlet.ThrowTerminatingError($_);
}
$Before = $String.Substring(0, $StartIndex);
$Content = $String.Substring($StartIndex, $EndIndex - $StartIndex);
$After = $String.Substring($EndIndex);
return "$Before$ColourSequence$Content$($PSStyle.Reset)$After";
}
function Format-RemoveEmptyLine {
[CmdletBinding()]
[OutputType([String])]
param(
[Parameter(Mandatory)]
[String]$String,
[Parameter()]
[Switch]$RemoveFinalNewLine
)
if ([String]::IsNullOrEmpty($String)) {
return $null;
}
for ($i = 0; $i -lt $String.Length; $i++) {
$Char = $String[$i];
if ($Char -eq "`n" -and ($Char -eq "`n" -or ($RemoveFinalNewLine -and $i -eq ($String.Length - 1)))) {
$String = $String.Remove($i, 1);
$i--;
}
}
return $String;
}
function Format-TrimToConsoleWidth {
[CmdletBinding()]
[OutputType({[PSCustomObject]@{
String = [String];
FocusRange = [Int];
}})]
param(
[Parameter(Mandatory)]
[String]$Line,
[Parameter(Mandatory)]
[ValidateSet('Left', 'Right', 'Both')]
[String]$TrimType,
[Parameter(HelpMessage = '
A range within the line that should not be touched while trimming.
Note that this can prevent the line from being trimmed to the console width if the range is too large.
')]
[Tuple[int,int]]$EnsureKeeping,
[Parameter()]
[Int]$Padding = 0,
[Parameter(DontShow)]
[Int]$EllipsisLength = 3
)
$Padding = $Padding + ($EllipsisLength * 2);
$ConsoleWidth = $Host.UI.RawUI.BufferSize.Width - $Padding;
$Line = (Format-TrimKeepingMultilineIndent -String $Line -TrimType Both).String;
if ($Line.Length -le $ConsoleWidth) {
return [PSCustomObject]@{
String = $Line;
KeepStartIndex = $EnsureKeeping.Item1;
};
}