-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcore.ps1
More file actions
2121 lines (2094 loc) · 70.8 KB
/
Copy pathcore.ps1
File metadata and controls
2121 lines (2094 loc) · 70.8 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
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '', Scope = 'Function', Target = 'Invoke-Operator')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Deny-Value')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Find-FirstIndex')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Get-Value')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Invoke-DropWhile_')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Invoke-ObjectMerge')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Invoke-Omit')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Invoke-Once')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Invoke-PropertyTransform')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Invoke-Reduce')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Invoke-Zip')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Invoke-ZipWith')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'Join-StringsWithGrammar')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'New-PropertyExpression')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Scope = 'Function', Target = 'New-RegexString')]
Param()
function ConvertFrom-Pair {
<#
.SYNOPSIS
Creates an object from an array of keys and an array of values. Key/Value pairs with higher index take precedence.
.EXAMPLE
@('a', 'b', 'c'), @(1, 2, 3) | fromPair
# @{ a = 1; b = 2; c = 3 }
#>
[CmdletBinding()]
[Alias('fromPair')]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[Array] $InputObject
)
Begin {
function Invoke-FromPair {
Param(
[Parameter(Position = 0)]
[Array] $InputObject
)
if ($InputObject.Count -gt 0) {
$Callback = {
Param($Acc, $Item)
$Key, $Value = $Item
$Acc.$Key = $Value
}
Invoke-Reduce -Items ($InputObject | Invoke-Zip) -Callback $Callback -InitialValue @{}
}
}
Invoke-FromPair $InputObject
}
End {
Invoke-FromPair $Input
}
}
function ConvertTo-OrderedDictionary {
<#
.SYNOPSIS
Converts a hashtable to an ordered hashtable.
Acts as passthru for odered dictionary inputs.
.EXAMPLE
@{ a = 1; b = 2; c = 3 } | ConvertTo-OrderedDictionary
#>
[CmdletBinding()]
[OutputType([System.Collections.Specialized.OrderedDictionary])]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
$InputObject,
[Parameter(Mandatory = $False, Position = 1)]
[String] $Property = 'Key'
)
switch ($InputObject) {
{ $_ -is [System.Collections.Specialized.OrderedDictionary] } {
$InputObject
}
{ $_ -is [System.Collections.Hashtable] } {
$Result = [Ordered]@{}
foreach ($Item in ($InputObject.GetEnumerator() | Sort-Object -Property $Property)) {
$Key = $Item.Key
$Result.add($Key, $InputObject[$Key])
}
$Result
}
{ $_ -is [System.Management.Automation.PSCustomObject] } {
$Result = [Ordered]@{}
foreach ($Item in $InputObject.PSObject.Properties) {
$Result.add($Item.Name, $Item.Value)
}
$Result
}
default {
$InputObject
}
}
}
function ConvertTo-Pair {
<#
.SYNOPSIS
Converts an object into two arrays - keys and values.
Note: The order of the output arrays are not guaranteed to be consistent with input object key/value pairs.
.EXAMPLE
@{ a = 1; b = 2; c = 3 } | toPair
# @('c', 'b', 'a'), @(3, 2, 1)
#>
[CmdletBinding()]
[Alias('toPair')]
[OutputType([Array])]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[PSObject] $InputObject
)
Process {
switch ($InputObject.GetType().Name) {
'PSCustomObject' {
$Properties = $InputObject.PSObject.Properties
$Keys = $Properties | Select-Object -ExpandProperty Name
$Values = $Properties | Select-Object -ExpandProperty Value
@($Keys, $Values)
}
'Hashtable' {
$Keys = $InputObject.GetEnumerator() | Select-Object -ExpandProperty Name
$Values = $InputObject.GetEnumerator() | Select-Object -ExpandProperty Value
@($Keys, $Values)
}
default { $InputObject }
}
}
}
function Deny-Empty {
<#
.SYNOPSIS
Remove empty string values from pipeline chains
.EXAMPLE
'a', 'b', '', 'd' | Deny-Empty
# 'a', 'b', 'd'
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[AllowNull()]
[AllowEmptyString()]
[Array] $InputObject
)
Begin {
$IsNotEmptyString = { -not ($_ -is [String]) -or ($_.Length -gt 0) }
if ($InputObject.Count -gt 0) {
$InputObject | Where-Object $IsNotEmptyString
}
}
End {
if ($Input.Count -gt 0) {
$Input | Where-Object $IsNotEmptyString
}
}
}
function Deny-Null {
<#
.SYNOPSIS
Remove null values from pipeline chains
.EXAMPLE
1, 2, $Null, 4 | Deny-Null
# 1, 2, 4
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[AllowNull()]
[AllowEmptyString()]
[Array] $InputObject
)
Begin {
$IsNotNull = { $Null -ne $_ }
if ($InputObject.Count -gt 0) {
$InputObject | Where-Object $IsNotNull
}
}
End {
if ($Input.Count -gt 0) {
$Input | Where-Object $IsNotNull
}
}
}
function Deny-Value {
<#
.SYNOPSIS
Remove string values equal to -Value parameter
.EXAMPLE
'a', 'b', 'a', 'a' | Deny-Value -Value 'b'
# 'a', 'a', 'a'
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True, Position = 1)]
[Array] $InputObject,
[Parameter(Mandatory = $True, Position = 0)]
$Value
)
Begin {
$IsNotValue = { $_ -ne $Value }
if ($InputObject.Count -gt 0) {
$InputObject | Where-Object $IsNotValue
}
}
End {
if ($Input.Count -gt 0) {
$Input | Where-Object $IsNotValue
}
}
}
function Find-FirstIndex {
<#
.SYNOPSIS
Helper function to return index of first array item that returns true for a given predicate
(default predicate returns true if value is $True)
.EXAMPLE
Find-FirstIndex -Values $False, $True, $False
# 1
.EXAMPLE
Find-FirstIndex -Values 1, 1, 1, 2, 1, 1 -Predicate { $_ -eq 2 }
# 3
.EXAMPLE
1, 1, 1, 2, 1, 1 | Find-FirstIndex -Predicate { $_ -eq 2 }
# 3
Note the use of the unary comma operator
.EXAMPLE
1, 1, 1, 2, 1, 1 | Find-FirstIndex -Predicate { Param($X) $X -eq 2 }
# 3
#>
[CmdletBinding()]
[OutputType([Int])]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[Array] $Values,
[ScriptBlock] $Predicate = { $_ -eq $True },
[Int] $DefaultIndex = -1
)
Begin {
function Find-FirstIndex_ {
Param(
[Parameter(Position = 0)]
[Array] $Values
)
if ($Values.Count -gt 0) {
$Results = New-Object 'System.Collections.ArrayList'
$UseAutomaticVariable = ($Predicate | Get-ParameterList).Name.Count -eq 0
$Powershell = if ($UseAutomaticVariable) {
[Powershell]::Create()
}
foreach ($Value in $Values) {
$Condition = if ($UseAutomaticVariable) {
$Null = $Powershell.AddCommand('Set-Variable').AddParameter('Name', '_').AddParameter('Value', $Value).AddScript($Predicate)
$Powershell.Invoke()
} else {
& $Predicate $Value
}
if ($Condition) {
$Index = [Array]::IndexOf($Values, $Value)
[Void]$Results.Add($Index)
}
}
if ($Results.Count -gt 0) {
$Results | Select-Object -First 1
} else {
$DefaultIndex
}
}
}
Find-FirstIndex_ $Values
}
End {
Find-FirstIndex_ $Input
}
}
function Get-Property {
<#
.SYNOPSIS
Helper function intended to streamline getting property values within pipelines.
.PARAMETER Name
Property name (or array index). Also works with dot-separated paths for nested properties.
For array-like inputs, $X,$Y | prop '0.1.2' is the same as $X[0][1][2],$Y[0][1][2] (see examples)
.EXAMPLE
'hello', 'world' | prop 'Length'
# 5, 5
.EXAMPLE
,@(1, 2, 3, @(4, 5, 6, @(7, 8, 9))) | prop '3.3.2'
# 9
# Note the leading comma
#>
[CmdletBinding()]
[Alias('prop')]
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True)]
$InputObject,
[Parameter(Position = 0)]
[ValidatePattern('^-?[\w\.]+$')]
[String] $Name
)
Begin {
function Test-NumberLike {
Param(
[String] $Value
)
$AsNumber = $Value -as [Int]
$AsNumber -or ($AsNumber -eq 0)
}
function Get-PropertyMaybe {
Param(
[Parameter(Position = 0)]
$InputObject,
[Parameter(Position = 1)]
[String] $Name
)
if ((Test-Enumerable $InputObject) -and (Test-NumberLike $Name)) {
$InputObject[$Name]
} else {
$InputObject.$Name
}
}
}
Process {
if ($Name -match '\.') {
$Result = $InputObject
$Properties = $Name -split '\.'
foreach ($Property in $Properties) {
$Result = Get-PropertyMaybe $Result $Property
}
$Result
} else {
Get-PropertyMaybe $InputObject $Name
}
}
}
function Invoke-Chunk {
<#
.SYNOPSIS
Creates an array of elements split into groups the length of Size. If array can't be split evenly, the final chunk will be the remaining elements.
.EXAMPLE
1..10 | chunk -s 3
# @(1, 2, 3), @(4, 5, 6), @(7, 8, 9), @(10)
#>
[CmdletBinding()]
[Alias('chunk')]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[Array] $InputObject,
[Parameter(Position = 1)]
[Alias('s')]
[Int] $Size = 0
)
Begin {
function Invoke-Chunk_ {
Param(
[Parameter(Position = 0)]
[Array] $InputObject,
[Parameter(Position = 1)]
[Int] $Size = 0
)
$InputSize = $InputObject.Count
if ($InputSize -gt 0) {
if ($Size -gt 0 -and $Size -lt $InputSize) {
$Index = 0
$Arrays = New-Object 'System.Collections.ArrayList'
for ($Count = 1; $Count -le ([Math]::Ceiling($InputSize / $Size)); $Count++) {
[Void]$Arrays.Add($InputObject[$Index..($Index + $Size - 1)])
$Index += $Size
}
$Arrays
} else {
$InputObject
}
}
}
Invoke-Chunk_ $InputObject $Size
}
End {
Invoke-Chunk_ $Input $Size
}
}
function Invoke-DropWhile {
<#
.SYNOPSIS
Create slice of array excluding elements dropped from the beginning
.PARAMETER Predicate
Function that returns $True or $False
.EXAMPLE
1..10 | dropWhile { $_ -lt 6 }
# 6, 7, 8, 9, 10
.EXAMPLE
40..45 | dropWhile { Param($X) $X -ne 42 }
# 42, 43, 44, 45
#>
[CmdletBinding()]
[Alias('dropwhile')]
Param(
[Parameter(Mandatory = $True, Position = 1, ValueFromPipeline = $True)]
[Array] $InputObject,
[Parameter(Mandatory = $True, Position = 0)]
[ScriptBlock] $Predicate
)
Begin {
function Invoke-DropWhile_ {
Param(
[Parameter(Position = 1)]
[Array] $InputObject,
[Parameter(Position = 0)]
[ScriptBlock] $Predicate
)
if ($InputObject.Count -gt 0) {
$UseAutomaticVariable = ($Predicate | Get-ParameterList).Name.Count -eq 0
if ($UseAutomaticVariable) {
$Continue = $False
$Powershell = [Powershell]::Create()
foreach ($Item in $InputObject) {
$Null = $Powershell.AddCommand('Set-Variable').AddParameter('Name', '_').AddParameter('Value', $Item).AddScript($Predicate)
$Condition = $Powershell.Invoke()
if (-not $Condition -or $Continue) {
$Continue = $True
$Item
}
}
} else {
$Items = switch ($InputObject.GetType().Name) {
'Char[]' {
$InputObject | ForEach-Object { "${_}" }
}
default {
$InputObject
}
}
[System.Linq.Enumerable]::SkipWhile($Items, [Func[Object, Bool]]$Predicate)
}
}
}
if ($InputObject.Count -eq 1 -and $InputObject[0].GetType().Name -eq 'String') {
$Result = Invoke-DropWhile_ $Predicate $InputObject[0].ToCharArray()
$Result -join ''
} else {
Invoke-DropWhile_ $Predicate $InputObject
}
}
End {
if ($Input.Count -eq 1 -and $Input[0].GetType().Name -eq 'String') {
$Result = Invoke-DropWhile_ $Predicate $Input.ToCharArray()
$Result -join ''
} else {
Invoke-DropWhile_ $Predicate $Input
}
}
}
function Invoke-Flatten {
<#
.SYNOPSIS
Recursively flatten array
.EXAMPLE
@(1, @(2, 3, @(4, 5))) | flatten
# 1, 2, 3, 4, 5
#>
[CmdletBinding()]
[Alias('flatten')]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[Array] $Values
)
Begin {
function Invoke-Flat {
Param(
[Parameter(Position = 0)]
[Array] $Values
)
if ($Values.Count -gt 0) {
$MaxCount = $Values | ForEach-Object { $_.Count } | Get-Maximum
if ($MaxCount -gt 1) {
Invoke-Flat ($Values | ForEach-Object { $_ } | Where-Object { $Null -ne $_ })
} else {
$Values
}
}
}
Invoke-Flat $Values
}
End {
Invoke-Flat $Input
}
}
function Invoke-InsertString {
<#
.SYNOPSIS
Easily insert strings within other strings
.PARAMETER At
Index
.EXAMPLE
'abce' | insert 'd' -At 3
# 'abcde
#>
[CmdletBinding()]
[Alias('insert')]
[OutputType([String])]
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True)]
[String] $To,
[Parameter(Mandatory = $True, Position = 0)]
[String] $Value,
[Parameter(Mandatory = $True)]
[Int] $At
)
Process {
if ($At -le $To.Length -and $At -ge 0) {
$To.Substring(0, $At) + $Value + $To.Substring($At, $To.length - $At)
} else {
$To
}
}
}
function Invoke-Method {
<#
.SYNOPSIS
Invokes method with pased name of a given object. The next two positional arguments after the method name are provided to the invoked method.
.EXAMPLE
' foo',' bar',' baz' | method 'TrimStart'
# 'foo', 'bar', 'baz'
.EXAMPLE
1, 2, 3 | method 'CompareTo' 2
# -1, 0, 1
.EXAMPLE
$Arguments = 'Substring', 0, 3
'abcdef', '123456', 'foobar' | method @Arguments
# 'abc', '123', 'foo'
#>
[CmdletBinding()]
[Alias('method')]
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True)]
$InputObject,
[Parameter(Mandatory = $True, Position = 0)]
[ValidatePattern('^-?\w+$')]
[String] $Name,
[Parameter(Position = 1)]
$ArgumentOne,
[Parameter(Position = 2)]
$ArgumentTwo
)
Process {
$Methods = $InputObject | Get-Member -MemberType Method | Select-Object -ExpandProperty Name
$ScriptMethods = $InputObject | Get-Member -MemberType ScriptMethod | Select-Object -ExpandProperty Name
$ParameterizedProperties = $InputObject | Get-Member -MemberType ParameterizedProperty | Select-Object -ExpandProperty Name
if ($Name -in ($Methods + $ScriptMethods + $ParameterizedProperties)) {
if ($Null -ne $ArgumentOne) {
if ($Null -ne $ArgumentTwo) {
$InputObject.$Name($ArgumentOne, $ArgumentTwo)
} else {
$InputObject.$Name($ArgumentOne)
}
} else {
$InputObject.$Name()
}
} else {
"==> $InputObject does not have a(n) `"$Name`" method" | Write-Verbose
$InputObject
}
}
}
function Invoke-ObjectInvert {
<#
.SYNOPSIS
Returns a new object with the keys of the given object as values, and the values of the given object, which are coerced to strings, as keys.
Note: A duplicate value in the passed object will become a key in the inverted object with an array of keys that had the duplicate value as a value.
.EXAMPLE
@{ foo = 'bar' } | invert
# @{ bar = 'foo' }
.EXAMPLE
@{ a = 1; b = 2; c = 1 } | invert
# @{ '1' = 'a','c'; '2' = 'b' }
#>
[CmdletBinding()]
[Alias('invert')]
[OutputType([System.Collections.Hashtable])]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[PSObject] $InputObject
)
Process {
$Data = $InputObject
$Keys, $Values = $Data | ConvertTo-Pair
$GroupedData = @($Keys, $Values) | Invoke-Zip | Group-Object { $_[1] }
if ($Keys.Count -gt 1) {
$Callback = {
Param($Acc, [String]$Key)
$Acc.$Key = $GroupedData |
Where-Object { $_.Name -eq $Key } |
Select-Object -ExpandProperty Group |
ForEach-Object { $_[0] } |
Sort-Object
}
$GroupedData |
Select-Object -ExpandProperty Name |
Invoke-Reduce -Callback $Callback -InitialValue @{}
} else {
if ($Data.GetType().Name -eq 'PSCustomObject') {
[PSCustomObject]@{ $Values = $Keys }
} else {
@{ $Values = $Keys }
}
}
}
}
function Invoke-ObjectMerge {
<#
.SYNOPSIS
Merge two or more hashtables or custom objects. The result will be of the same type as the first item passed.
.PARAMETER Force
Default behavior is to not overwrite existing values. Set this parameter to $True to overwrite existing values.
.EXAMPLE
@{ a = 1 }, @{ b = 2 }, @{ c = 3 } | merge
# @{ a = 1; b = 2; c = 3 }
.EXAMPLE
[PSCustomObject]@{ a = 1 }, [PSCustomObject]@{ b = 2 } | merge
# [PSCustomObject]@{ a = 1; b = 2 }
.EXAMPLE
@{ a = 1 }, @{ a = 3 } | merge
# @{ a = 1 }
@{ a = 1 }, @{ a = 3 } | merge -Force
# @{ a = 3 }
#>
[CmdletBinding()]
[Alias('merge')]
[OutputType([System.Collections.Hashtable])]
Param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[Array] $InputObject,
[Switch] $InPlace,
[Switch] $Force
)
Begin {
function Set-ObjectKeyValue {
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True)]
$InputObject,
[Parameter(Mandatory = $True)]
$Key,
$Value
)
$Type = $InputObject.GetType().Name
if ($Type -eq 'PSCustomObject') {
$InputObject | Add-Member -MemberType NoteProperty -Name $Key -Value $Value
} else {
$InputObject.$Key = $Value
}
$InputObject
}
function Test-ObjectKeyValueNullEmpty {
Param(
[Parameter(Mandatory = $True, Position = 0)]
$InputObject,
[Parameter(Mandatory = $True, Position = 1)]
$Key
)
$Type = $InputObject.GetType().Name
$Keys = if ($Type -eq 'PSCustomObject') {
$InputObject.PSObject.Properties.Name
} else {
$InputObject.keys
}
if ($Keys -contains $Key) {
[String]::IsNullOrEmpty($InputObject.$Key)
} else {
$True
}
}
function Invoke-Merge {
Param(
[Parameter(Position = 0)]
[Array] $InputObject
)
if ($Null -ne $InputObject) {
$Result = if ($InputObject.Count -gt 1) {
$InputObject | Invoke-Reduce -Callback {
Param($Acc, $Item)
$Type = $Item.GetType().Name
$ItemCount = if ($Type -eq 'PSCustomObject') {
$Item.PSObject.Properties.Name.Length
} else {
$Item.Count
}
switch ($ItemCount) {
0 {
# Return nothing
}
1 {
$K, $V = $Item | ConvertTo-Pair
if ((Test-ObjectKeyValueNullEmpty $Acc $K) -or $Force) {
$Acc | Set-ObjectKeyValue -Key $K -Value $V | Out-Null
}
}
default {
$Item | ConvertTo-Pair | Invoke-Zip | ForEach-Object {
$Key, $Value = $_
if ((Test-ObjectKeyValueNullEmpty $Acc $Key) -or $Force) {
$Acc | Set-ObjectKeyValue -Key $Key -Value $Value | Out-Null
}
}
}
}
}
} else {
$InputObject
}
if ($InPlace) {
$InputObject = $Result
} else {
if ($InputObject[0].GetType().Name -eq 'PSCustomObject') {
[PSCustomObject]$Result
} else {
$Result
}
}
}
}
Invoke-Merge $InputObject
}
End {
Invoke-Merge $Input
}
}
function Invoke-Once {
<#
.SYNOPSIS
Higher-order function that takes a function and returns a function that can only be executed a certain number of times
.PARAMETER Times
Number of times passed function can be called (default is 1, hence the name - Once)
.EXAMPLE
$Function:test = Invoke-Once { 'Should only see this once' | Write-Color -Red }
1..10 | ForEach-Object { test }
.EXAMPLE
$Function:greet = Invoke-Once { "Hello $($Args[0])" | Write-Color -Red }
greet 'World'
# no subsequent greet functions are executed
greet 'Jim'
greet 'Bob'
# Functions returned by Invoke-Once can accept arguments
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True, Position = 0)]
[ScriptBlock] $Function,
[Int] $Times = 1
)
{
if ($Script:Count -lt $Times) {
& $Function @Args
$Script:Count++
}
}.GetNewClosure()
}
function Invoke-Omit {
<#
.SYNOPSIS
Create an object composed of the omitted object properties
.EXAMPLE
@{ a = 1; b = 2; c = 3 } | omit a
# @{ b = 2; c = 3 }
#>
[CmdletBinding()]
[Alias('omit')]
[OutputType([Hashtable])]
[OutputType([PSCustomObject])]
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True)]
[PSObject] $From,
[Parameter(Position = 0)]
[Array] $Name
)
Process {
$Type = $From.GetType().Name
$Name = $Name | ForEach-Object { $_ }
switch ($Type) {
'PSCustomObject' {
$Result = [PSCustomObject]@{}
$Keys = $From.PSObject.Properties.Name
foreach ($Property in $Keys.Where( { $_ -notin $Name })) {
$Result | Add-Member -MemberType NoteProperty -Name $Property -Value $From.$Property
}
$Result
}
'Hashtable' {
$Result = @{}
$Keys = $From.keys
foreach ($Property in $Keys.Where( { $_ -notin $Name })) {
$Result.$Property = $From.$Property
}
$Result
}
default {
$Result = @{}
$Result
}
}
}
}
function Invoke-Operator {
<#
.SYNOPSIS
Helper function intended mainly for use within quick one-line pipeline chains
.EXAMPLE
@(1, 2, 3), @(4, 5, 6), @(7, 8, 9) | op join ''
# '123', '456', '789'
#>
[CmdletBinding()]
[Alias('op')]
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True)]
$InputObject,
[Parameter(Mandatory = $True, Position = 0)]
[ValidatePattern('^-?[\w%\+-\/\*]+$')]
[ValidateLength(1, 12)]
[String] $Name,
[Parameter(Mandatory = $True, Position = 1)]
[Array] $Arguments
)
Process {
try {
if ($Arguments.Count -eq 1) {
$Operand = if ([String]::IsNullOrEmpty($Arguments)) { "''" } else { "`"``$Arguments`"" }
$Expression = "`$InputObject $(if ($Name.Length -eq 1) { '' } else { '-' })$Name $Operand"
"==> Executing: $Expression" | Write-Verbose
Invoke-Expression $Expression
} else {
$Arguments = $Arguments | ForEach-Object { "`"``$_`"" }
$Expression = "`$InputObject -$Name $($Arguments -join ',')"
"==> Executing: $Expression" | Write-Verbose
Invoke-Expression $Expression
}
} catch {
"==> $InputObject does not support the `"$Name`" operator" | Write-Verbose
$InputObject
}
}
}
function Invoke-Partition {
<#
.SYNOPSIS
Creates an array of elements split into two groups, the first of which contains elements that the predicate returns truthy for, the second of which contains elements that the predicate returns falsey for.
The predicate is invoked with one argument (each element of the passed array)
.EXAMPLE
$IsEven = { $_ % 2 -eq 0 }
1..10 | Invoke-Partition $IsEven
# @(@(2, 4, 6, 8, 10), @(1, 3, 5, 7, 9))
.EXAMPLE
$IsEven = { Param($X) $X % 2 -eq 0 }
1..10 | Invoke-Partition $IsEven
# @(@(2, 4, 6, 8, 10), @(1, 3, 5, 7, 9))
#>
[CmdletBinding()]
[Alias('partition')]
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True)]
[Array] $InputObject,
[Parameter(Mandatory = $True, Position = 0)]
[ScriptBlock] $Predicate
)
Begin {
function Invoke-Partition_ {
Param(
[Parameter(Position = 0)]
[Array] $InputObject,
[Parameter(Position = 1)]
[ScriptBlock] $Predicate
)
if ($InputObject.Count -gt 1) {
$Left = @()
$Right = @()
$UseAutomaticVariable = ($Predicate | Get-ParameterList).Name.Count -eq 0
$Powershell = if ($UseAutomaticVariable) {
[Powershell]::Create()
}
foreach ($Item in $InputObject) {
$Condition = if ($UseAutomaticVariable) {
$Null = $Powershell.AddCommand('Set-Variable').AddParameter('Name', '_').AddParameter('Value', $Item).AddScript($Predicate)
$Powershell.Invoke()
} else {
& $Predicate $Item
}
if ($Condition) {
$Left += $Item
} else {
$Right += $Item
}
}
@($Left, $Right)
}
}
Invoke-Partition_ $InputObject $Predicate
}
End {
Invoke-Partition_ $Input $Predicate
}
}
function Invoke-Pick {
<#
.SYNOPSIS
Create an object composed of the picked object properties
.DESCRIPTION
This function behaves very much like Select-Object, but with normalized behavior that works on hashtables and custom objects.
.PARAMETER All
Include non-existent properties. For non-existent properties, set value to -EmptyValue.
.EXAMPLE
@{ a = 1; b = 2; c = 3 } | pick 'a','c'
# @{ a = 1; c = 3 }
#>
[CmdletBinding()]
[Alias('pick')]
[OutputType([Hashtable])]
[OutputType([PSCustomObject])]
Param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True)]
[PSObject] $From,
[Parameter(Position = 0)]
[Array] $Name,
[Switch] $All,
[AllowNull()]
[AllowEmptyString()]
$EmptyValue = $Null
)
Process {
$Type = $From.GetType().Name
switch ($Type) {
'PSCustomObject' {
$Result = [PSCustomObject]@{}
$Keys = $From.PSObject.Properties.Name
foreach ($Property in $Name.Where( { $_ -in $Keys })) {
$Result | Add-Member -MemberType NoteProperty -Name $Property -Value $From.$Property
}
if ($All) {
foreach ($Property in $Name.Where( { $_ -notin $Keys })) {
$Result | Add-Member -MemberType NoteProperty -Name $Property -Value $EmptyValue
}
}
$Result
}
'Hashtable' {
$Result = @{}
$Keys = $From.keys
foreach ($Property in $Name.Where( { $_ -in $Keys })) {
$Result.$Property = $From.$Property
}
if ($All) {
foreach ($Property in $Name.Where( { $_ -notin $Keys })) {
$Result.$Property = $EmptyValue
}
}
$Result
}
default {
$Result = @{}
if ($All) {
foreach ($Property in $Name) {
$Result.$Property = $EmptyValue
}
}
$Result
}
}
}
}
function Invoke-PropertyTransform {
<#
.SYNOPSIS
Helper function that can be used to rename object keys and transform values.
.PARAMETER Transform
The Transform function that can be a simple identity function or complex reducer (as used by Redux.js and React.js)
The Transform function can use pipeline values or the automatice variables, $Name and $Value which represent the associated old key name and original value, respectively.
A reducer that would transform the values with the keys, 'foo' or 'bar', migh look something like this:
$Reducer = {
Param($Name, $Value)
switch ($Name) {
'foo' { ... }
'bar' { ... }
Default { $Value }
}
}
.PARAMETER Lookup
Dictionary lookup object that will map old key names to new key names.
Example:
$Lookup = @{
foobar = 'foo_bar'
Name = 'first_name'
}
.EXAMPLE
$Data = @{}
$Data | Add-member -NotePropertyName 'fighter_power_level' -NotePropertyValue 90
$Lookup = @{
level = 'fighter_power_level'
}
$Reducer = {
Param($Value)
($Value * 100) + 1
}
$Data | Invoke-PropertyTransform -Lookup $Lookup -Transform $Reducer