PSRedstone.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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460

class Redstone {
    hidden  [string]                $_Action                = $null
    hidden  [hashtable]             $_CimInstance           = $null
    hidden  [hashtable]             $_Env                   = $null
    hidden  [hashtable]             $_OS                    = $null
    hidden  [hashtable]             $_Vars                  = $null
    hidden  [string]                $_Product               = $null
    hidden  [hashtable]             $_ProfileList           = $null
    hidden  [string]                $_Publisher             = $null
    hidden  [string]                $_Version               = 'None'
    [int]                           $ExitCode               = 0
    [System.Collections.ArrayList]  $Exiting                = @()
    [bool]                          $IsElevated             = $null
    [hashtable]                     $Settings               = @{}

    # Use the default settings, don't read any of the settings in from the registry. In production this is never set.
    [bool]                          $OnlyUseDefaultSettings = $false
    [hashtable]                     $Debug                  = @{}

    #region Instantiation
    static Redstone() {
        # Creating some custom setters that update other properties, like Log Paths, when related properties are changed.
        Update-TypeData -TypeName 'Redstone' -MemberName 'Action' -MemberType 'ScriptProperty' -Value {
            # Getter
            return $this._Action
        } -SecondValue {
            param($value)
            # Setter
            $this._Action = $value
            $this.SetUpLog()
        } -Force
        Update-TypeData -TypeName 'Redstone' -MemberName 'CimInstance' -MemberType 'ScriptProperty' -Value {
            # Getter
            $className = $MyInvocation.Line.Split('.')[2]
            return $this.GetCimInstance($className, $true)
        } -Force
        Update-TypeData -TypeName 'Redstone' -MemberName 'Env' -MemberType 'ScriptProperty' -Value {
            # Getter
            if (-not $this._Env) {
                # This is the Lazy Loading logic.
                $this.SetUpEnv()
            }
            return $this._Env
        } -Force
        Update-TypeData -TypeName 'Redstone' -MemberName 'OS' -MemberType 'ScriptProperty' -Value {
            # Getter
            if (-not $this._OS) {
                # This is the Lazy Loading logic.
                $this.SetUpOS()
            }
            return $this._OS
        } -Force
        Update-TypeData -TypeName 'Redstone' -MemberName 'Vars' -MemberType 'ScriptProperty' -Value {
            # Getter
            if (-not $this._Vars) {
                # This is the Lazy Loading logic.
                $this.SetUpVars()
            }
            return $this._Vars
        } -SecondValue {
            param($value)
            # Setter
            $this._Vars = $value
        } -Force
        Update-TypeData -TypeName 'Redstone' -MemberName 'Product' -MemberType 'ScriptProperty' -Value {
            # Getter
            return $this._Product
        } -SecondValue {
            param($value)
            # Setter
            $this._Product = $value
            $this.SetUpLog()
        } -Force
        Update-TypeData -TypeName 'Redstone' -MemberName 'ProfileList' -MemberType 'ScriptProperty' -Value {
            # Getter
            if (-not $this._ProfileList) {
                # This is the Lazy Loading logic.
                $this.SetUpProfileList()
            }
            return $this._ProfileList
        } -Force
        Update-TypeData -TypeName 'Redstone' -MemberName 'Publisher' -MemberType 'ScriptProperty' -Value {
            # Getter
            return $this._Publisher
        } -SecondValue {
            param($value)
            # Setter
            $this._Publisher = $value
            $this.SetUpLog()
        } -Force
        Update-TypeData -TypeName 'Redstone' -MemberName 'Version' -MemberType 'ScriptProperty' -Value {
            # Getter
            return $this._Version
        } -SecondValue {
            param($value)
            # Setter
            $this._Version = $value
            $this.SetUpLog()
        } -Force
    }

    Redstone() {
        $this.SetUpSettings()
        $this.Settings.JSON = @{}

        $settingsFiles = @(
            [IO.FileInfo] ([IO.Path]::Combine($PWD.ProviderPath, 'settings.json'))
            [IO.FileInfo] ([IO.Path]::Combine(([IO.FileInfo] $this.Debug.PSCallStack[2].ScriptName).Directory.FullName, 'settings.json'))
            [IO.FileInfo] ([IO.Path]::Combine(([IO.DirectoryInfo] $PWD.ProviderPath).Parent, 'settings.json'))
            [IO.FileInfo] ([IO.Path]::Combine(([IO.FileInfo] $this.Debug.PSCallStack[2].ScriptName).Directory.Parent.FullName, 'settings.json'))
        )

        foreach ($location in $settingsFiles) {
            if ($location.Exists) {
                $this.Settings.JSON.File = $location
                $this.Settings.JSON.Data = Get-Content $this.Settings.JSON.File.FullName | ConvertFrom-Json
                break
            }
        }

        if (-not $this.Settings.JSON.File.Exists) {
            if (Get-Variable 'settings' -Scope 'script' -ErrorAction 'Ignore') {
                if ($script:settings.Keys -notcontains 'Publisher') {
                    Throw [System.IO.FileNotFoundException] ('Settings must contain Publisher: {0}' -f ($script:settings | ConvertTo-Json))
                }
                if ($script:settings.Keys -notcontains 'Product') {
                    Throw [System.IO.FileNotFoundException] ('Settings must contain Product: {0}' -f ($script:settings | ConvertTo-Json))
                }
                if ($script:settings.Keys -notcontains 'Version') {
                    Throw [System.IO.FileNotFoundException] ('Settings must contain Version: {0}' -f ($script:settings | ConvertTo-Json))
                }
            } else {
                Throw [System.IO.FileNotFoundException] ('Could NEITHER find the settings variable nor a file at any of these locations: {0}' -f ($settingsFiles.FullName -join ', '))
            }
        }

        $this.SetDefaultSettingsFromRegistry($this.Settings.Registry.KeyRoot)
        $this.SetPSDefaultParameterValues($this.Settings.Functions)

        $this.set__Publisher($this.Settings.JSON.Data.Publisher)
        $this.set__Product($this.Settings.JSON.Data.Product)
        $this.set__Version($this.Settings.JSON.Data.Version)
        $this.set__Action($(
            if ($this.Settings.JSON.Data.Action) {
                $this.Settings.JSON.Data.Action
            } else {
                $scriptName = ($this.Debug.PSCallStack | Where-Object {
                    ([IO.FileInfo] $_.ScriptName).Name -ne ([IO.FileInfo] $this.Debug.PSCallStack[0].ScriptName).Name
                } | Select-Object -First 1).ScriptName
                ([IO.FileInfo] $scriptName).BaseName
            }
        ))

        $this.SetUpLog()
    }

    Redstone([IO.FileInfo] $Settings) {
        $this.SetUpSettings()

        $this.Settings.JSON = @{}
        $this.Settings.JSON.File = [IO.FileInfo] $Settings
        if ($this.Settings.JSON.File.Exists) {
            $this.Settings.JSON.Data = Get-Content $this.Settings.JSON.File.FullName | ConvertFrom-Json
        } else {
            Throw [System.IO.FileNotFoundException] $this.Settings.JSON.File.FullName
        }

        $this.SetDefaultSettingsFromRegistry($this.Settings.Registry.KeyRoot)
        $this.SetPSDefaultParameterValues($this.Settings.Functions)

        $this.set__Publisher($this.Settings.JSON.Data.Publisher)
        $this.set__Product($this.Settings.JSON.Data.Product)
        $this.set__Version($this.Settings.JSON.Data.Version)
        $this.set__Action($(
            if ($this.Settings.JSON.Data.Action) {
                $this.Settings.JSON.Data.Action
            } else {
                $scriptName = ($this.Debug.PSCallStack | Where-Object {
                    ([IO.FileInfo] $_.ScriptName).Name -ne ([IO.FileInfo] $this.Debug.PSCallStack[0].ScriptName).Name
                } | Select-Object -First 1).ScriptName
                ([IO.FileInfo] $scriptName).BaseName
            }
        ))

        $this.SetUpLog()
    }
    
    Redstone([PSObject] $Settings) {
        $this.SetUpSettings()

        $this.Settings.JSON = @{}
        $this.Settings.JSON.Data = $Settings

        $this.SetDefaultSettingsFromRegistry($this.Settings.Registry.KeyRoot)
        $this.SetPSDefaultParameterValues($this.Settings.Functions)

        $this.set__Publisher($this.Settings.JSON.Data.Publisher)
        $this.set__Product($this.Settings.JSON.Data.Product)
        $this.set__Version($this.Settings.JSON.Data.Version)
        $this.set__Action($(
            if ($this.Settings.JSON.Data.Action) {
                $this.Settings.JSON.Data.Action
            } else {
                $scriptName = ($this.Debug.PSCallStack | Where-Object {
                    ([IO.FileInfo] $_.ScriptName).Name -ne ([IO.FileInfo] $this.Debug.PSCallStack[0].ScriptName).Name
                } | Select-Object -First 1).ScriptName
                ([IO.FileInfo] $scriptName).BaseName
            }
        ))

        $this.SetUpLog()
    }

    Redstone([string] $Publisher, [string] $Product, [string] $Version, [string] $Action) {
        $this.SetUpSettings()

        $this.SetDefaultSettingsFromRegistry($this.Settings.Registry.KeyRoot)
        $this.SetPSDefaultParameterValues($this.Settings.Functions)

        $this.set__Publisher($Publisher)
        $this.set__Product($Product)
        $this.set__Version($Version)
        $this.set__Action($Action)

        $this.SetUpLog()
    }
    #endregion Instantiation

    #region Settings
    hidden [void] SetUpSettings() {
        <#
        This is the original Settings
        #>

        $this.Debug = @{
            MyInvocation = $MyInvocation
            PSCallStack = (Get-PSCallStack)
        }

        $this.IsElevated = (New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
        $this.Settings = @{}

        $regKeyPSRedstone = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\com.github.VertigoRay\PSRedstone'
        $this.Settings.Registry = @{
            KeyRoot = $this.GetSetting($regKeyPSRedstone, 'RegistryKeyRoot', $regKeyPSRedstone)
        }
    }

    hidden [string] GetSetting([string] $Key, [string] $Name, [string] $Default) {
        $item = Get-Item ('env:{0}' -f $Name) -ErrorAction 'Ignore'
        if ($item.Value) {
            return ($item.Value -as [string])
        } else {
            return ((Get-RegistryValueOrDefault $Key $Name $Default) -as [string])
        }
    }
    #endregion Settings

    #region CimInstance
    hidden [object] GetCimInstance($ClassName) {
        return $this.GetCimInstance($ClassName, $false, $false)
    }

    hidden [object] GetCimInstance($ClassName, $ReturnCimInstanceNotClass) {
        return $this.GetCimInstance($ClassName, $ReturnCimInstanceNotClass, $false)
    }

    hidden [object] GetCimInstance($ClassName, $ReturnCimInstanceNotClass, $Refresh) {
        # This is the Lazy Loading logic.
        if (-not $this._CimInstance) {
            $this._CimInstance = @{}
        }
        if ($Refresh -or ($ClassName -and -not $this._CimInstance.$ClassName)) {
            $this._CimInstance.Set_Item($ClassName, (Get-CimInstance -ClassName $ClassName -ErrorAction 'Ignore'))
        }
        if ($ReturnCimInstanceNotClass) {
            return $this._CimInstance
        } else {
            return $this._CimInstance.$ClassName
        }
    }

    [object] CimInstanceRefreshed($ClassName) {
        return $this.GetCimInstance($ClassName, $false, $true)
    }
    #endregion CimInstance

    #region Debug Overrides
    hidden [bool] Is64BitOperatingSystem() {
        if ('Is64BitOperatingSystem' -in $this.Debug.Keys) {
            return $this.Debug.Is64BitOperatingSystem
        } else {
            return ([System.Environment]::Is64BitOperatingSystem)
        }
    }

    hidden [System.Collections.DictionaryEntry] Is64BitOperatingSystem([bool] $Override) {
        # Used for Pester Testing
        $this.Debug.Is64BitOperatingSystem = $Override
        return ($this.Debug.GetEnumerator() | Where-Object{ $_.Name -eq 'Is64BitOperatingSystem' })
    }

    hidden [bool] Is64BitProcess() {
        if ('Is64BitProcess' -in $this.Debug.Keys) {
            return $this.Debug.Is64BitProcess
        } else {
            return ([System.Environment]::Is64BitProcess)
        }
    }

    hidden [System.Collections.DictionaryEntry] Is64BitProcess([bool] $Override) {
        # Used for Pester Testing
        $this.Debug.Is64BitProcess = $Override
        return ($this.Debug.GetEnumerator() | Where-Object{ $_.Name -eq 'Is64BitProcess' })
    }
    #endregion Debug Overrides

    #region Env
    hidden [void] SetUpEnv() {
        # This section

        $this._Env = @{}
        if ($this.Is64BitOperatingSystem()) {
            # x64 OS
            if ($this.Is64BitProcess()) {
                # x64 Process
                $this._Env.CommonProgramFiles = $env:CommonProgramFiles
                $this._Env.'CommonProgramFiles(x86)' = ${env:CommonProgramFiles(x86)}
                $this._Env.PROCESSOR_ARCHITECTURE = $env:PROCESSOR_ARCHITECTURE
                $this._Env.ProgramFiles = $env:ProgramFiles
                $this._Env.'ProgramFiles(x86)' = ${env:ProgramFiles(x86)}
                $this._Env.System32 = "${env:SystemRoot}\System32"
                $this._Env.SysWOW64 = "${env:SystemRoot}\SysWOW64"
            } else {
                # Running as x86 on x64 OS
                $this._Env.CommonProgramFiles = $env:CommonProgramW6432
                $this._Env.'CommonProgramFiles(x86)' = ${env:CommonProgramFiles(x86)}
                $this._Env.PROCESSOR_ARCHITECTURE = $env:PROCESSOR_ARCHITEW6432
                $this._Env.ProgramFiles = $env:ProgramW6432
                $this._Env.'ProgramFiles(x86)' = ${env:ProgramFiles(x86)}
                $this._Env.System32 = "${env:SystemRoot}\SysNative"
                $this._Env.SysWOW64 = "${env:SystemRoot}\SysWOW64"
            }
        } else {
            # x86 OS
            $this._Env.CommonProgramFiles = $env:CommonProgramFiles
            $this._Env.'CommonProgramFiles(x86)' = $env:CommonProgramFiles
            $this._Env.PROCESSOR_ARCHITECTURE = $env:PROCESSOR_ARCHITECTURE
            $this._Env.ProgramFiles = $env:ProgramFiles
            $this._Env.'ProgramFiles(x86)' = $env:ProgramFiles
            $this._Env.System32 = "${env:SystemRoot}\System32"
            $this._Env.SysWOW64 = "${env:SystemRoot}\System32"
        }
    }
    #endregion Env

    #region Log
    hidden [void] SetUpLog() {
        $this.Settings.Log = @{}

        if ($this.IsElevated) {
            $private:Directory = [IO.DirectoryInfo] "${env:SystemRoot}\Logs\Redstone"
        } else {
            $private:Directory = [IO.DirectoryInfo] "${env:Temp}\Logs\Redstone"
        }

        if (-not $private:Directory.Exists) {
            New-Item -ItemType 'Directory' -Path $private:Directory.FullName -Force | Out-Null
            $private:Directory.Refresh()
        }

        $this.Settings.Log.File = [IO.FileInfo] (Join-Path $private:Directory.FullName ('{0} {1} {2} {3}.log' -f $this.Publisher, $this.Product, $this.Version, $this.Action))
        $this.Settings.Log.FileF = (Join-Path $private:Directory.FullName ('{0} {1} {2} {3}.{{0}}.log' -f $this.Publisher, $this.Product, $this.Version, $this.Action)) -as [string]
        $this.PSDefaultParameterValuesSetUp()
    }
    #endregion Log

    #region OS
    hidden [void] SetUpOS() {
        $this._OS = @{}
        [bool]   $this._OS.Is64BitOperatingSystem = [System.Environment]::Is64BitOperatingSystem
        [bool]   $this._OS.Is64BitProcess = [System.Environment]::Is64BitProcess

        [bool] $this._OS.Is64BitProcessor = ($this.GetCimInstance('Win32_Processor')| Where-Object { $_.DeviceID -eq 'CPU0' }).AddressWidth -eq '64'
        [bool]      $this._OS.IsMachinePartOfDomain = $this.GetCimInstance('Win32_ComputerSystem').PartOfDomain

        [string]    $this._OS.MachineWorkgroup = $null
        [string]    $this._OS.MachineADDomain = $null
        [string]    $this._OS.LogonServer = $null
        [string]    $this._OS.MachineDomainController = $null
        if ($this._OS.IsMachinePartOfDomain) {
            [string] $this._OS.MachineADDomain = $this.GetCimInstance('Win32_ComputerSystem').Domain | Where-Object { $_ } | ForEach-Object { $_.ToLower() }
            try {
                [string] $this._OS.LogonServer = $env:LOGONSERVER | Where-Object { (($_) -and (-not $_.Contains('\\MicrosoftAccount'))) } | ForEach-Object { $_.TrimStart('\') } | ForEach-Object { ([System.Net.Dns]::GetHostEntry($_)).HostName }
                [string] $this._OS.MachineDomainController = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().FindDomainController().Name
            } catch {
                Write-Verbose 'Not in AD'
            }
        } else {
            [string] $this._OS.MachineWorkgroup = $this.GetCimInstance('Win32_ComputerSystem').Domain | Where-Object { $_ } | ForEach-Object { $_.ToUpper() }
        }
        [string]    $this._OS.MachineDNSDomain = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().DomainName | Where-Object { $_ } | ForEach-Object { $_.ToLower() }
        [string]    $this._OS.MachineSid = ((Get-LocalUser | Select-Object -First 1).SID).AccountDomainSID.ToString()
        [string]    $this._OS.UserDNSDomain = $env:USERDNSDOMAIN | Where-Object { $_ } | ForEach-Object { $_.ToLower() }
        [string]    $this._OS.UserDomain = $env:USERDOMAIN | Where-Object { $_ } | ForEach-Object { $_.ToUpper() }
        [string]    $this._OS.Name = $this.GetCimInstance('Win32_OperatingSystem').Name.Trim()
        [string]    $this._OS.ShortName = (($this._OS.Name).Split('|')[0] -replace '\w+\s+(Windows [\d\.]+\s+\w+)', '$1').Trim()
        [string]    $this._OS.ShorterName = (($this._OS.Name).Split('|')[0] -replace '\w+\s+(Windows [\d\.]+)\s+\w+', '$1').Trim()
        [string]    $this._OS.ServicePack = $this.GetCimInstance('Win32_OperatingSystem').CSDVersion
        [version]   $this._OS.Version = [System.Environment]::OSVersion.Version
        # Get the operating system type
        [int32]     $this._OS.ProductType = $this.GetCimInstance('Win32_OperatingSystem').ProductType
        [bool]      $this._OS.IsServerOS = [bool]($this._OS.ProductType -eq 3)
        [bool]      $this._OS.IsDomainControllerOS = [bool]($this._OS.ProductType -eq 2)
        [bool]      $this._OS.IsWorkStationOS = [bool]($this._OS.ProductType -eq 1)
        switch ($this._OS.ProductType) {
            1       { [string] $this._OS.ProductTypeName = 'Workstation' }
            2       { [string] $this._OS.ProductTypeName = 'Domain Controller' }
            3       { [string] $this._OS.ProductTypeName = 'Server' }
            default { [string] $this._OS.ProductTypeName = 'Unknown' }
        }
    }
    #endregion OS

    #region Profile List
    hidden [void] SetUpProfileList() {
        Write-Debug 'GETTER: ProfileList'
        if (-not $this._ProfileList) {
            Write-Debug 'GETTER: Setting up ProfileList'
            $this._ProfileList = @{}
            $regProfileListPath = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
            $regProfileList = Get-Item $regProfileListPath
            foreach ($property in $regProfileList.Property) {
                $value = if ($dirInfo = (Get-ItemProperty -Path $regProfileListPath).$property -as [IO.DirectoryInfo]) {
                    $dirInfo
                } else {
                    (Get-ItemProperty -Path $regProfileListPath).$property
                }
                $this._ProfileList.Add($property, $value)
            }

            [System.Collections.ArrayList] $this._ProfileList.Profiles = @()
            foreach ($userProfile in (Get-ChildItem $regProfileListPath)) {
                [hashtable] $user = @{}
                $user.Add('SID', $userProfile.PSChildName)
                $user.Add('Path', ((Get-ItemProperty "${regProfileListPath}\$($userProfile.PSChildName)").ProfileImagePath -as [IO.DirectoryInfo]))
                $objSID = New-Object System.Security.Principal.SecurityIdentifier($user.SID)
                try {
                    $objUser = $objSID.Translate([System.Security.Principal.NTAccount])
                    $domainUsername = $objUser.Value
                } catch [System.Management.Automation.MethodInvocationException] {
                    Write-Warning "Unable to translate the SID ($($user.SID)) to a Username."
                    $domainUsername = $null
                }

                $domain, $username = $domainUsername.Split('\')
                try {
                    $user.Add('Domain', $domain.Trim())
                } catch {
                    $user.Add('Domain', $null)
                }
                try {
                    $user.Add('Username', $username.Trim())
                } catch {
                    $user.Add('Username', $domainUsername)
                }
                ($this._ProfileList.Profiles).Add($user) | Out-Null
            }
        }
    }
    #endregion Profile List

    #region Vars
    hidden [void] SetUpVars() {
        $this.Settings.Registry.KeyOrg = $this.GetSetting($this.Settings.Registry.KeyRoot, 'RegistryKeyOrg', [IO.Path]::Combine($this.Settings.Registry.KeyRoot, 'Org'))
        $this.Settings.Registry.KeyOrgRecurse = $this.GetSetting($this.Settings.Registry.KeyRoot, 'RegistryKeyOrgRecurse', $false)
        $this.Settings.Registry.KeyPublisherParent = $this.GetSetting($this.Settings.Registry.KeyRoot, 'RegistryKeyPublisherParent', [IO.Path]::Combine($this.Settings.Registry.KeyRoot, 'Software'))
        $this.Settings.Registry.KeyPublisherRecurse = $this.GetSetting($this.Settings.Registry.KeyRoot, 'RegistryKeyPublisherRecurse', $false)
        $this.Settings.Registry.KeyProductParent = $this.GetSetting($this.Settings.Registry.KeyRoot, 'RegistryKeyProductParent', [IO.Path]::Combine($this.Settings.Registry.KeyPublisherParent, $this._Publisher))
        $this.Settings.Registry.KeyProductRecurse = $this.GetSetting($this.Settings.Registry.KeyRoot, 'RegistryKeyProductRecurse', $true)

        $this.Settings.Org = @{}
        $query = @{
            Key = $this.Settings.Registry.KeyOrg
            Recurse = $this.Settings.Registry.KeyOrgRecurse
        }
        $this.Settings.Org = Get-RegistryKeyAsHashTable @query
        $this.Vars = Get-RegistryKeyAsHashTable @query

        $this.Settings.Publisher = @{}
        $query = @{
            Key = [IO.Path]::Combine($this.Settings.Registry.KeyPublisherParent, $this._Publisher)
            Recurse = $this.Settings.Registry.KeyPublisherRecurse
        }
        $this.Settings.Publisher = Get-RegistryKeyAsHashTable @query
        $this.Vars = Get-RegistryKeyAsHashTable @query

        $this.Settings.Product = @{}
        $query = @{
            Key = [IO.Path]::Combine($this.Settings.Registry.KeyProductParent, $this._Product)
            Recurse = $this.Settings.Registry.KeyProductRecurse
        }
        $this.Settings.Product = Get-RegistryKeyAsHashTable @query
        $this.Vars = Get-RegistryKeyAsHashTable @query
    }

    [PSObject] GetVar([string] $Path) {
        return (Get-HashtableValue -Hashtable $this._Vars -Path $Path)
    }

    [PSObject] GetVar([string] $Path, [PSObject] $Default) {
        return (Get-HashtableValue -Hashtable $this._Vars -Path $Path -Default $Default)
    }
    #endregion Vars

    #region PSDefaultParameterValues
    hidden [void] PSDefaultParameterValuesSetUp() {
        $_prefix = (Get-Module 'PSRedstone').Prefix

        # $global:PSDefaultParameterValues.Set_Item(('*-{0}*:LogFileF' -f $_prefix), $this.Settings.Log.FileF)
        # $global:PSDefaultParameterValues.Set_Item(('*-{0}*:LogFileF' -f $_prefix), $this.Settings.Log.FileF)
        foreach ($_exportedCommand in (Get-Module 'PSRedstone').ExportedCommands.Keys) {
            if ((Get-Command $_exportedCommand).Parameters.Keys -contains 'LogFile') {
                $global:PSDefaultParameterValues.Set_Item(('{0}:LogFile' -f $_exportedCommand), $this.Settings.Log.File.FullName)
            }
            if ((Get-Command $_exportedCommand).Parameters.Keys -contains 'LogFileF') {
                $global:PSDefaultParameterValues.Set_Item(('{0}:LogFileF' -f $_exportedCommand), $this.Settings.Log.FileF)
            }
        }

        $_onlyUseDefaultSettings = $this.GetRegOrDefault('Settings\Functions\Get-RegistryValueOrDefault', 'OnlyUseDefaultSettings', $false)
        $global:PSDefaultParameterValues.Set_Item(('Get-{0}RegistryValueOrDefault:OnlyUseDefaultSettings' -f $_prefix), $_onlyUseDefaultSettings)

        # https://github.com/VertigoRay/PSWriteLog/wiki
        $global:PSDefaultParameterValues.Set_Item('Write-Log:FilePath', $this.Settings.Log.File.FullName)
    }

    hidden [void] SetPSDefaultParameterValues([hashtable] $FunctionParameters) {
        if ($FunctionParameters) {
            foreach ($function in $FunctionParameters.GetEnumerator()) {
                Write-Debug ('[Redstone::SetPSDefaultParameterValues] Function Type: [{0}]' -f $function.GetType().FullName)
                Write-Debug ('[Redstone::SetPSDefaultParameterValues] Function: {0}: {1}' -f $function.Name, ($function.Value | ConvertTo-Json))
                foreach ($parameter in $function.Value.GetEnumerator()) {
                    Write-Debug ('[Redstone::SetPSDefaultParameterValues] Parameter: {0}: {1}' -f $parameter.Name, ($parameter.Value | ConvertTo-Json))
                    Write-Debug ('[Redstone::SetPSDefaultParameterValues] PSDefaultParameterValues: {0}:{1} :: {2}' -f $function.Name, $parameter.Name, $parameter.Value)
                    $global:PSDefaultParameterValues.Set_Item(('{0}:{1}' -f $function.Name, $parameter.Name), $parameter.Value)
                }
            }
        }
    }
    #endregion PSDefaultParameterValues

    #region Registry
    hidden [psobject] GetRegOrDefault($RegistryKey, $RegistryValue, $DefaultValue) {
        Write-Verbose "[Redstone GetRegOrDefault] > $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
        Write-Debug "[Redstone GetRegOrDefault] Function Invocation: $($MyInvocation | Out-String)"

        if ($this.OnlyUseDefaultSettings) {
            Write-Verbose "[Redstone GetRegOrDefault] OnlyUseDefaultSettings Set; Returning: ${DefaultValue}"
            return $DefaultValue
        }

        try {
            $ret = Get-ItemPropertyValue -Path ('Registry::{0}\{1}' -f $this.Settings.Registry.KeyRoot, $RegistryKey) -Name $RegistryValue -ErrorAction 'Stop'
            Write-Verbose "[Redstone GetRegOrDefault] Registry Set; Returning: ${ret}"
            return $ret
        } catch [System.Management.Automation.PSArgumentException] {
            Write-Verbose "[Redstone GetRegOrDefault] Registry Not Set; Returning Default: ${DefaultValue}"
            # This isn't a real error, so I don't want it in the error record.
            # This is a weird way to remove the record, but I've seen in testing where $Error length is 0, and
            # I don't understand it. However, this catches that error and ensure it doesn't end up on the $Error.
            # Ref: https://ci.appveyor.com/project/VertigoRay/psredstone/builds/46036142
            if ($Error.Count -gt 0) {
                $Error.RemoveAt(0)
            }
            return $DefaultValue
        } catch [System.Management.Automation.ItemNotFoundException] {
            Write-Verbose "[Redstone GetRegOrDefault] Registry Not Set; Returning Default: ${DefaultValue}"
            # This isn't a real error, so I don't want it in the error record.
            # This is a weird way to remove the record, but I've seen in testing where $Error length is 0, and
            # I don't understand it. However, this catches that error and ensure it doesn't end up on the $Error.
            # Ref: https://ci.appveyor.com/project/VertigoRay/psredstone/builds/46036142
            if ($Error.Count -gt 0) {
                $Error.RemoveAt(0)
            }
            return $DefaultValue
        }
    }

    hidden [void] SetDefaultSettingsFromRegistrySubKey([hashtable] $Hash, [string] $Key) {
        foreach ($regValue in (Get-Item $Key -ErrorAction 'Ignore').Property) {
            $Hash.Set_Item($regValue, (Get-ItemProperty -Path $Key -Name $regValue).$regValue)
        }
    }

    [string] GetRegValueDoNotExpandEnvironmentNames($Key, $Value) {
        $item = Get-Item $Key
        if ($item) {
            return $item.GetValue($Value, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
        } else {
            return $null
        }
    }

    hidden [void] SetDefaultSettingsFromRegistry([string] $Key) {
        <#
        Dig through the Registry Key and import all the Keys and Values into the $global:Redstone objet.
 
        There's a fundamental flaw that I haven't addressed yet.
        - if there's a value and sub-key with the same name at the same key level, the sub-key won't be processed.
        #>

        if (Test-Path $Key) {
            $this.SetDefaultSettingsFromRegistrySubKey($this.Settings, $Key)

            foreach ($item in (Get-ChildItem $Key -Recurse -ErrorAction 'Ignore')) {
                $private:psPath = $item.PSPath.Split(':')[-1].Replace($Key.Split(':')[-1], $null)
                $private:node = $this.Settings
                foreach ($child in ($private:psPath.Trim('\').Split('\'))) {
                    if (-not $node.$child) {
                        [hashtable] $node.$child = @{}
                    }
                    $node = $node.$child
                }

                $this.SetDefaultSettingsFromRegistrySubKey($node, $item.PSPath)
            }
        }
    }
    #endregion Registry

    #region Special Folders
    [psobject] GetSpecialFolders() {
        $specialFolders = [ordered] @{}
        foreach ($folder in ([Environment+SpecialFolder]::GetNames([Environment+SpecialFolder]) | Sort-Object)) {
            $specialFolders.Add($folder, $this.GetSpecialFolder($folder))
        }
        return ([psobject] $specialFolders)
    }

    [IO.DirectoryInfo] GetSpecialFolder([string] $Name) {
        return ([Environment]::GetFolderPath($Name) -as [IO.DirectoryInfo])
    }
    #endregion Special Folders

    #region Quit
    [void] Quit() {
        Write-Debug ('[Redstone.Quit 0] > {0}' -f ($MyInvocation | Out-String))
        [void] $this.Quit(0, $true , 0)
    }

    [void] Quit($ExitCode = 0) {
        Write-Verbose ('[Redstone.Quit 1] > {0}' -f ($MyInvocation | Out-String))
        $this.ExitCode = if ($ExitCode -eq 'line_number') {
            (Get-PSCallStack)[1].Location.Split(':')[1].Replace('line', '') -as [int]
        } else {
            $ExitCode
        }
        [void] $this.Quit($this.ExitCode, $false , 55550000)
    }

    [void] Quit($ExitCode = 0, [boolean] $ExitCodeAdd = $false) {
        Write-Verbose ('[Redstone.Quit 1] > {0}' -f ($MyInvocation | Out-String))
        $this.ExitCode = if ($ExitCode -eq 'line_number') {
            (Get-PSCallStack)[1].Location.Split(':')[1].Replace('line', '') -as [int]
        } else {
            $ExitCode
        }
        [void] $this.Quit($this.ExitCode, $ExitCodeAdd , 55550000)
    }

    [void] Quit($ExitCode = 0, [boolean] $ExitCodeAdd = $false, [int] $ExitCodeErrorBase = 55550000) {
        Write-Debug ('[Redstone.Quit 3] > {0}' -f ($MyInvocation | Out-String))

        Write-Verbose ('[Redstone.Quit] ExitCode: {0}' -f $ExitCode)
        $this.ExitCode = if ($ExitCode -eq 'line_number') {
            (Get-PSCallStack)[1].Location.Split(':')[1].Replace('line', '') -as [int]
        } else {
            $ExitCode -as [int]
        }

        if ($ExitCodeAdd) {
            Write-Information ('[Redstone.Quit] ExitCodeErrorBase: {0}' -f $ExitCodeErrorBase)
            if (($this.ExitCode -lt 0) -and ($ExitCodeErrorBase -gt 0)) {
                # Always Exit positive
                Write-Verbose ('[Redstone.Quit] ExitCodeErrorBase: {0}' -f $ExitCodeErrorBase)
                $ExitCodeErrorBase = $ExitCodeErrorBase * -1
                Write-Verbose ('[Redstone.Quit] ExitCodeErrorBase: {0}' -f $ExitCodeErrorBase)
            }

            if (([string] $this.ExitCode).Length -gt 4) {
                Write-Warning "[Redstone.Quit] ExitCode should not be added to Base when more than 4 digits. Doing it anyway ..."
            }

            if ($this.ExitCode -eq 0) {
                Write-Warning "[Redstone.Quit] ExitCode 0 being added may cause failure; not sure if this is expected. Doing it anyway ..."
            }

            $this.ExitCode = $this.ExitCode + $ExitCodeErrorBase
        }

        Write-Information ('[Redstone.Quit] ExitCode: {0}' -f $this.ExitCode)

        # Debug.Quit.DoNotExit is used in Pester testing.
        if (-not $this.Debug.Quit.DoNotExit) {
            $global:Host.SetShouldExit($ExitCode)
            Exit $ExitCode
        }
    }
    #endregion Quit
}
<#
.SYNOPSIS
Is the current process elevated (running as administrator)?
.OUTPUTS
[bool]
.EXAMPLE
Assert-IsElevated
Returns `$true` if you're running as an administrator.
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#assert-iselevated
#>

function Assert-IsElevated {
    [CmdletBinding()]
    [OutputType([bool])]
    Param()

    Write-Verbose ('[Assert-IsElevated] >')
    Write-Debug ('[Assert-IsElevated] > {0}' -f ($MyInvocation | Out-String))

    $isElevated = (New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    Write-Verbose ('[Assert-IsElevated] IsElevated: {0}' -f $isElevated)

    return $isElevated
}
<#
.SYNOPSIS
Wait, up to a timeout value, to check if current thread is able to acquire an exclusive lock on a system mutex.
.DESCRIPTION
A mutex can be used to serialize applications and prevent multiple instances from being opened at the same time.
Wait, up to a timeout (default is 1 millisecond), for the mutex to become available for an exclusive lock.
This is an internal script function and should typically not be called directly.
.PARAMETER MutexName
The name of the system mutex.
.PARAMETER MutexWaitTimeInMilliseconds
The number of milliseconds the current thread should wait to acquire an exclusive lock of a named mutex. Default is: $Redstone.Settings.'Test-IsMutexAvailable'.MutexWaitTimeInMilliseconds
A wait time of -1 milliseconds means to wait indefinitely. A wait time of zero does not acquire an exclusive lock but instead tests the state of the wait handle and returns immediately.
.EXAMPLE
Assert-IsMutexAvailable -MutexName 'Global\_MSIExecute' -MutexWaitTimeInMilliseconds 500
.EXAMPLE
Assert-IsMutexAvailable -MutexName 'Global\_MSIExecute' -MutexWaitTimeInMilliseconds (New-TimeSpan -Minutes 5).TotalMilliseconds
.EXAMPLE
Assert-IsMutexAvailable -MutexName 'Global\_MSIExecute' -MutexWaitTimeInMilliseconds (New-TimeSpan -Seconds 60).TotalMilliseconds
.NOTES
- [_MSIExecute Mutex](https://learn.microsoft.com/en-us/windows/win32/msi/-msiexecute-mutex)
 
> Copyright â’¸ 2015 - PowerShell App Deployment Toolkit Team
>
> Copyright â’¸ 2023 - Raymond Piller (VertigoRay)
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions/#assert-ismutexavailable
#>

function Assert-IsMutexAvailable {
    [CmdletBinding()]
    [OutputType([bool])]
    Param (
        [Parameter(Mandatory = $true)]
        [ValidateLength(1,260)]
        [string]
        $MutexName,

        [Parameter(Mandatory = $false)]
        [ValidateRange(-1, [int32]::MaxValue)]
        [int32]
        $MutexWaitTimeInMilliseconds = 300000 #5min
    )

    Write-Information "> $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
    Write-Debug "Function Invocation: $($MyInvocation | Out-String)"


    ## Initialize Variables
    [timespan] $MutexWaitTime = [timespan]::FromMilliseconds($MutexWaitTimeInMilliseconds)
    if ($MutexWaitTime.TotalMinutes -ge 1) {
        [string] $WaitLogMsg = "$($MutexWaitTime.TotalMinutes) minute(s)"
    } elseif ($MutexWaitTime.TotalSeconds -ge 1) {
        [string] $WaitLogMsg = "$($MutexWaitTime.TotalSeconds) second(s)"
    } else {
        [string] $WaitLogMsg = "$($MutexWaitTime.Milliseconds) millisecond(s)"
    }
    [boolean] $IsUnhandledException = $false
    [boolean] $IsMutexFree = $false
    [Threading.Mutex] $OpenExistingMutex = $null

    Write-Information "Check to see if mutex [$MutexName] is available. Wait up to [$WaitLogMsg] for the mutex to become available."
    try {
        ## Using this variable allows capture of exceptions from .NET methods. Private scope only changes value for current function.
        $private:previousErrorActionPreference = $ErrorActionPreference
        $ErrorActionPreference = 'Stop'

        ## Open the specified named mutex, if it already exists, without acquiring an exclusive lock on it. If the system mutex does not exist, this method throws an exception instead of creating the system object.
        [Threading.Mutex] $OpenExistingMutex = [Threading.Mutex]::OpenExisting($MutexName)
        ## Attempt to acquire an exclusive lock on the mutex. Use a Timespan to specify a timeout value after which no further attempt is made to acquire a lock on the mutex.
        $IsMutexFree = $OpenExistingMutex.WaitOne($MutexWaitTime, $false)
    } catch [Threading.WaitHandleCannotBeOpenedException] {
        ## The named mutex does not exist
        $IsMutexFree = $true
    } catch [ObjectDisposedException] {
        ## Mutex was disposed between opening it and attempting to wait on it
        $IsMutexFree = $true
    } catch [UnauthorizedAccessException] {
        ## The named mutex exists, but the user does not have the security access required to use it
        $IsMutexFree = $false
    } catch [Threading.AbandonedMutexException] {
        ## The wait completed because a thread exited without releasing a mutex. This exception is thrown when one thread acquires a mutex object that another thread has abandoned by exiting without releasing it.
        $IsMutexFree = $true
    } catch {
        $IsUnhandledException = $true
        ## Return $true, to signify that mutex is available, because function was unable to successfully complete a check due to an unhandled exception. Default is to err on the side of the mutex being available on a hard failure.
        Write-Error "Unable to check if mutex [$MutexName] is available due to an unhandled exception. Will default to return value of [$true]. `n$(Resolve-Error)"
        $IsMutexFree = $true
    } finally {
        if ($IsMutexFree) {
            if (-not $IsUnhandledException) {
                Write-Information "Mutex [$MutexName] is available for an exclusive lock."
            }
        } else {
            if ($MutexName -eq 'Global\_MSIExecute') {
                ## Get the command line for the MSI installation in progress
                try {
                    [string] $msiInProgressCmdLine = Get-CimInstance -Class 'Win32_Process' -Filter "name = 'msiexec.exe'" -ErrorAction 'Stop' | Where-Object { $_.CommandLine } | Select-Object -ExpandProperty 'CommandLine' | Where-Object { $_ -match '\.msi' } | ForEach-Object { $_.Trim() }
                } catch {
                    Write-Warning ('Unexpected/Unhandled Error caught: {0}' -f $_)
                }
                Write-Warning "Mutex [$MutexName] is not available for an exclusive lock because the following MSI installation is in progress [$msiInProgressCmdLine]."
            } else {
                Write-Information "Mutex [$MutexName] is not available because another thread already has an exclusive lock on it."
            }
        }

        if (($null -ne $OpenExistingMutex) -and ($IsMutexFree)) {
            ## Release exclusive lock on the mutex
            $null = $OpenExistingMutex.ReleaseMutex()
            $OpenExistingMutex.Close()
        }
        if ($private:previousErrorActionPreference) {
            $ErrorActionPreference = $private:previousErrorActionPreference
        }
    }

    return $IsMutexFree
}
<#
.SYNOPSIS
Is the current process running in a non-interactive shell?
.DESCRIPTION
There are two ways to determine if the current process is in a non-interactive shell:
 
- See if the user environment is marked as interactive.
- See if PowerShell was launched with the -NonInteractive
.EXAMPLE
Assert-IsNonInteractiveShell
If you're typing this into PowerShell, you should see `$false`.
.NOTES
- [Powershell test for noninteractive mode](https://stackoverflow.com/a/34098997/615422)
- [Environment.UserInteractive Property](https://learn.microsoft.com/en-us/dotnet/api/system.environment.userinteractive)
- [About PowerShell.exe: NonInteractive](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-noninteractive)
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#assert-isnoninteractiveshell
#>

function Assert-IsNonInteractiveShell {
    [CmdletBinding()]
    [OutputType([bool])]
    param()

    # Test each Arg for match of abbreviated '-NonInteractive' command.
    $NonInteractive = [Environment]::GetCommandLineArgs() | Where-Object{ $_ -like '-NonI*' }

    if ([Environment]::UserInteractive -and -not $NonInteractive) {
        # We are in an interactive shell.
        return $false
    }

    return $true
}
<#
.SYNOPSIS
Close the supplied process.
.DESCRIPTION
The supplied process is expected to be a program and have a visible window.
This function will attempt to safely close the window before force killing the process.
It's a little safer than just doing a `Stop-Process -Force`.
.EXAMPLE
Get-Process code | Close-Program
.EXAMPLE
$codes = Get-Process code; $codes | Close-Program -SleepSeconds [math]::Ceiling($codes.Count / 2)
#>

function Close-Program {
    [CmdletBinding()]
    param (
        # Process to close.
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [System.Diagnostics.Process]
        $Process,

        # The number of seconds to wait after closing the main window before we force kill.
        # If passing this in a pipeline, this is per pipeline item; otherwise, it is the wait time for all processes.
        [Parameter(Mandatory = $false)]
        [int32]
        $SleepSeconds = 1
    )
    process {
        foreach ($proc in $Process) {
            $Process | ForEach-Object { $_.CloseMainWindow() | Out-Null }

            # Wait for windows to close before attempting a force kill.
            $sw = [System.Diagnostics.Stopwatch]::new()
            $sw.Start()

            while ($Process.HasExited -contains $false) {
                Start-Sleep -Milliseconds 250
                if ($sw.Elapsed.TotalSeconds -gt $SleepSeconds) {
                    break
                }
            }

            # In case gracefull shutdown did not succeed, try hard kill
            $Process | Where-Object { -not $_.HasExited } | Stop-Process -Force
        }
    }
}
<#
.SYNOPSIS
Dismount a registry hive.
.DESCRIPTION
Dismount a hive to the registry.
.OUTPUTS
[void]
.PARAMETER Hive
The key object returned from `Mount-RegistryHive`.
.EXAMPLE
Dismount-RegistryHive -Hive $hive
 
Where `$hive` was created with:
 
```powershell
$hive = Mount-RegistryHive -DefaultUser
```
#>

function Dismount-RegistryHive ([Microsoft.Win32.RegistryKey] $Hive) {
    # Garbage Collection
    [gc]::Collect()

    $regLoad = @{
        FilePath = (Get-Command 'reg.exe').Source
        ArgumentList = @(
            'UNLOAD'
            $Hive
        )
    }
    $result = Invoke-Run $regLoad

    if ($result.Process.ExitCode) {
        # Non-Zero Exit Code
        Throw ($result.StdErr | Out-String)
    } else {
        return (Get-Item ('Registry::{0}' -f $defaultHive))
    }
}
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Dismount a WIM.
.DESCRIPTION
Dismount a WIM from the provided mount path.
.EXAMPLE
Dismount-Wim -MountPath $mountPath
 
Where `$mountPath` is the path returned by `Mount-Wim`.
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#dismount-wim
#>

function Dismount-Wim {
    [CmdletBinding()]
    [OutputType([void])]
    param (
        # Specifies a path to one or more locations.
        [Parameter(Mandatory = $true, Position = 0, HelpMessage = 'Path the WIM was mounted.')]
        [ValidateNotNullOrEmpty()]
        [IO.DirectoryInfo]
        $MountPath,

        [Parameter(Mandatory = $false, HelpMessage = 'Full path for the DISM log with {0} formatter to inject "DISM".')]
        [IO.FileInfo]
        $LogFileF
    )

    begin {
        Write-Verbose "[Dismount-Wim] > $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
        Write-Debug "[Dismount-Wim] Function Invocation: $($MyInvocation | Out-String)"

        $windowsImage = @{
            Path = $MountPath.FullName
            Discard = $true
            ErrorAction = 'Stop'
        }

        if ($LogFileF) {
            $windowsImage.Add('LogPath', ($LogFileF -f 'DISM'))
        }

        <#
            Script used inside of the Scheduled Task that's created, if needed.
        #>

        $mounted = {
            $mountedInvalid = Get-WindowsImage -Mounted | Where-Object { $_.MountStatus -eq 'Invalid' }
            $errorOccured = $false
            foreach ($mountedWim in $mountedInvalid) {
                $windowsImage = @{
                    Path = $mountedWim.Path
                    Discard = $true
                    ErrorAction = 'Stop'
                }

                try {
                    Dismount-WindowsImage @windowsImage
                } catch {
                    $errorOccured = $true
                }
            }

            if (-not $errorOccured) {
                Clear-WindowsCorruptMountPoint
                Unregister-ScheduledTask -TaskName 'Redstone Cleanup WIM' -Confirm:$false
            }
        }
        $encodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($mounted.ToString()))
        $cleanupTaskAction = @{
            Execute = 'powershell.exe'
            Argument = '-Exe Bypass -Win Hidden -NoProfile -NonInteractive -EncodedCommand {0}' -f $encodedCommand.tostring()
        }
    }

    process {
        ## dismount the WIM whether we succeeded or failed
        try {
            Write-Verbose "[Dismount-Wim] Dismount-WindowImage: $($windowsImage | ConvertTo-Json)"
            Dismount-WindowsImage @windowsImage
        } catch [System.Runtime.InteropServices.COMException] {
            Write-Warning ('[Dismount-Wim] [{0}] {1}' -f $_.Exception.GetType().FullName, $_.Exception.Message)
            if ($_.Exception.Message -eq 'The system cannot find the file specified.') {
                Throw $_
            } else {
                # $_.Exception.Message -eq 'The system cannot find the file specified.'
                ## failed to cleanly dismount, so set a task to cleanup after reboot

                Write-Verbose ('[Dismount-Wim] Scheduled Task Action: {0}' -f ($cleanupTaskAction | ConvertTo-Json))

                $scheduledTaskAction = New-ScheduledTaskAction @cleanupTaskAction
                $scheduledTaskTrigger = New-ScheduledTaskTrigger -AtStartup

                $scheduledTask = @{
                    Action = $scheduledTaskAction
                    Trigger = $scheduledTaskTrigger
                    TaskName = 'Redstone Cleanup WIM'
                    Description = 'Clean up WIM Mount points that failed to dismount properly.'
                    User = 'NT AUTHORITY\SYSTEM'
                    RunLevel = 'Highest'
                    Force = $true
                }
                Write-Verbose ('[Dismount-Wim] Scheduled Task: {0}' -f ($scheduledTask | ConvertTo-Json))
                Register-ScheduledTask @scheduledTask
            }
        }

        $clearWindowsCorruptMountPoint = @{}
        if ($LogFileF) {
            $windowsImage.Add('LogPath', ($LogFileF -f ('DISM')))
        }

        Clear-WindowsCorruptMountPoint @clearWindowsCorruptMountPoint
    }

    end {}
}
<#
.SYNOPSIS
Attempt to find the EXE in the provided Path.
.DESCRIPTION
This functions will go through three steps to find the provided EXE:
 
- Determine if you provided the full path to the EXE or if it's in the current directory.
- Determine if it can be found under any path in $env:PATH.
- Determine if the locations was registered in the registry.
 
If one of these is true, it'll stop looking and return the `IO.FileInfo` of the EXE.
.OUTPUTS
[IO.FileInfo]
.EXAMPLE
Get-ExeFileInfo 'notepad.exe'
.EXAMPLE
Get-ExeFileInfo 'chrome.exe'
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-exefileinfo
#>

function Get-ExeFileInfo {
    [CmdletBinding()]
    [OutputType([IO.FileInfo])]
    param(
        [Parameter(Mandatory = $true, Position = 0, HelpMessage = 'Name of the EXE to search for.')]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({
            if (([IO.FileInfo] $_).Extension -eq '.exe') {
                Write-Output $true
            } else {
                Throw ('The Path "{0}" has an unexpected extension "{1}"; expecting ".exe".' -f @(
                    $_
                    ([IO.FileInfo] $_).Extension
                ))
            }
        })]
        [string]
        $Path
    )

    Write-Information "[Get-ExeFileInfo] > $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
    Write-Debug "[Get-ExeFileInfo] Function Invocation: $($MyInvocation | Out-String)"

    if (([IO.FileInfo] $Path).Exists) {
        $result = $Path
    } elseif ($command = Get-Command $Path -ErrorAction 'Ignore') {
        $result = $command.Source
    } else {
        $appPath = ('Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{0}' -f $Path)
        if ($defaultPath = (Get-ItemProperty $appPath -ErrorAction 'Ignore').'(default)') {
            $result = $defaultPath
        } else {
            Write-Warning ('EXE file location not discoverable: {0}' -f $Path)
            $result = $Path
        }
    }
    return ([IO.FileInfo] $result.Trim('"'))
}
<#
.SYNOPSIS
This function is purely designed to make things easier when getting a value from a hashtable using a path in string form.
.DESCRIPTION
This function is purely designed to make things easier when getting a value from a hashtable using a path in string form.
It has the added benefit of returning a provided default value if the path doesn't exist.
.EXAMPLE
Get-HashtableValue -Hashtable $vars -Path 'Thing2.This2.That1' -Default 'nope'
 
Returns `221` from the following `$vars` hashtable:
 
```powershell
$vars = @{
    Thing1 = 1
    Thing2 = @{
        This1 = 21
        This2 = @{
            That1 = 221
            That2 = 222
            That3 = 223
            That4 = $null
        }
        This3 = 23
    }
    Thing3 = 3
}
```
.EXAMPLE
Get-HashtableValue -Hashtable $vars -Path 'Thing2.This2.That4' -Default 'nope'
 
Returns `$null` from the following `$vars` hashtable:
 
```powershell
$vars = @{
    Thing1 = 1
    Thing2 = @{
        This1 = 21
        This2 = @{
            That1 = 221
            That2 = 222
            That3 = 223
            That4 = $null
        }
        This3 = 23
    }
    Thing3 = 3
}
```
.EXAMPLE
Get-HashtableValue -Hashtable $vars -Path 'Thing2.This4' -Default 'nope'
 
Returns `"nope"` from the following `$vars` hashtable:
 
```powershell
$vars = @{
    Thing1 = 1
    Thing2 = @{
        This1 = 21
        This2 = @{
            That1 = 221
            That2 = 222
            That3 = 223
            That4 = $null
        }
        This3 = 23
    }
    Thing3 = 3
}
```
.EXAMPLE
$redstone.GetVar('Thing2.This2.That4', 'nope')
 
When being used to access `$redstone.Vars` there's a built-in method that calls this function a bit easier.
Returns `$null` from the following `$redstone.Vars` hashtable:
 
```powershell
$redstone.Vars = @{
    Thing1 = 1
    Thing2 = @{
        This1 = 21
        This2 = @{
            That1 = 221
            That2 = 222
            That3 = 223
            That4 = $null
        }
        This3 = 23
    }
    Thing3 = 3
}
```
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-hashtablevalue
#>

function Get-HashtableValue([hashtable] $Hashtable, [string] $Path, $Default = $null) {
    $parent, $leaf = $Path.Split('.', 2)

    if ($leaf) {
        return (Get-HashtableValue $Hashtable.$parent $leaf $Default)
    } elseif ($Hashtable.Keys -contains $parent) {
        return $Hashtable.$parent
    } else {
        return $Default
    }
}
<#
.SYNOPSIS
Retrieves information about installed applications.
.DESCRIPTION
Retrieves information about installed applications by querying the registry. You can specify an application name, a product code, or both.
Returns information about application publisher, name & version, product code, uninstall string, quiet uninstall string, install source, location, date, and application architecture.
.PARAMETER Name
The name of the application to retrieve information for. Performs a regex match on the application display name by default.
.PARAMETER Exact
Specifies that the named application must be matched using the exact name.
.PARAMETER WildCard
Specifies that the named application must be matched using a wildcard search.
.PARAMETER ProductCode
The product code of the application to retrieve information for.
.PARAMETER IncludeUpdatesAndHotfixes
Include matches against updates and hotfixes in results.
.PARAMETER UninstallRegKeys
Private Parameter; used for debug overrides.
.OUTPUTS
[hashtable[]]
.EXAMPLE
Get-InstalledApplication -Name 'Adobe Flash'
.EXAMPLE
Get-InstalledApplication -ProductCode '{1AD147D0-BE0E-3D6C-AC11-64F6DC4163F1}'
.NOTES
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-installedapplication
#>

function Get-InstalledApplication {
    [CmdletBinding(DefaultParameterSetName = 'Like')]
    [OutputType([hashtable[]])]
    Param (
        [Parameter(Mandatory = $false, Position = 0, ParameterSetName = 'Eq')]
        [Parameter(Mandatory = $false, Position = 0, ParameterSetName = 'Exact')]
        [Parameter(Mandatory = $false, Position = 0, ParameterSetName = 'Like')]
        [Parameter(Mandatory = $false, Position = 0, ParameterSetName = 'Regex')]
        [ValidateNotNullorEmpty()]
        [string[]]
        $Name = '*',

        [Parameter(Mandatory = $false, ParameterSetName = 'Eq')]
        [Parameter(Mandatory = $false, ParameterSetName = 'Exact')]
        [Parameter(Mandatory = $false, ParameterSetName = 'Like')]
        [Parameter(Mandatory = $false, ParameterSetName = 'Regex')]
        [switch]
        $CaseSensitive,

        [Parameter(Mandatory = $false, ParameterSetName = 'Exact')]
        [switch]
        $Exact,

        [Parameter(Mandatory = $false, ParameterSetName = 'Like')]
        [switch]
        $WildCard,

        [Parameter(Mandatory = $false, ParameterSetName = 'Regex')]
        [switch]
        $RegEx,

        [Parameter(Mandatory = $false, ParameterSetName = 'Productcode')]
        [ValidateNotNullorEmpty()]
        [string]
        $ProductCode,

        [Parameter(Mandatory = $false, ParameterSetName = 'Eq')]
        [Parameter(Mandatory = $false, ParameterSetName = 'Exact')]
        [Parameter(Mandatory = $false, ParameterSetName = 'Like')]
        [Parameter(Mandatory = $false, ParameterSetName = 'Regex')]
        [Parameter(Mandatory = $false, ParameterSetName = 'Productcode')]
        [switch]
        $IncludeUpdatesAndHotfixes,

        [ValidateNotNullorEmpty()]
        [string[]]
        $UninstallRegKeys = @(
            'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
            'HKLM:SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
        )
    )

    Write-Information "[Get-InstalledApplication] > $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
    Write-Information "[Get-InstalledApplication] ParameterSetName> $($PSCmdlet.ParameterSetName | ConvertTo-Json -Compress)"
    Write-Debug "[Get-InstalledApplication] Function Invocation: $($MyInvocation | Out-String)"


    if ($Name) {
        Write-Information "[Get-InstalledApplication] Get information for installed Application Name(s) [$($name -join ', ')]..."
    }
    if ($ProductCode) {
        Write-Information "[Get-InstalledApplication] Get information for installed Product Code [$ProductCode]..."
    }

    ## Enumerate the installed applications from the registry for applications that have the "DisplayName" property
    [psobject[]] $regKeyApplication = @()
    foreach ($regKey in $UninstallRegKeys) {
        Write-Verbose "[Get-InstalledApplication] Checking Key: ${regKey}"
        if (Test-Path -LiteralPath $regKey -ErrorAction 'SilentlyContinue' -ErrorVariable '+ErrorUninstallKeyPath') {
            [psobject[]] $UninstallKeyApps = Get-ChildItem -LiteralPath $regKey -ErrorAction 'SilentlyContinue' -ErrorVariable '+ErrorUninstallKeyPath'
            foreach ($UninstallKeyApp in $UninstallKeyApps) {
                Write-Verbose "[Get-InstalledApplication] Checking Key: $($UninstallKeyApp.PSChildName)"
                try {
                    [psobject] $regKeyApplicationProps = Get-ItemProperty -LiteralPath $UninstallKeyApp.PSPath -ErrorAction 'Stop'
                    if ($regKeyApplicationProps.DisplayName) { [psobject[]] $regKeyApplication += $regKeyApplicationProps }
                } catch {
                    Write-Warning "[Get-InstalledApplication] Unable to enumerate properties from registry key path [$($UninstallKeyApp.PSPath)].$(if (Get-Command 'Resolve-Error' -ErrorAction 'Ignore') { "`n{0}" -f (Resolve-Error) })"
                    continue
                }
            }
        }
    }
    if ($ErrorUninstallKeyPath) {
        Write-Warning "[Get-InstalledApplication] The following error(s) took place while enumerating installed applications from the registry.$(if (Get-Command 'Resolve-Error' -ErrorAction 'Ignore') { "`n{0}" -f (Resolve-Error -ErrorRecord $ErrorUninstallKeyPath) })"
    }

    ## Create a custom object with the desired properties for the installed applications and sanitize property details
    [Collections.ArrayList] $installedApplication = @()
    foreach ($regKeyApp in $regKeyApplication) {
        try {
            [string] $appDisplayName = ''
            [string] $appDisplayVersion = ''
            [string] $appPublisher = ''

            ## Bypass any updates or hotfixes
            if (-not $IncludeUpdatesAndHotfixes.IsPresent) {
                if ($regKeyApp.DisplayName -match '(?i)kb\d+') { continue }
                if ($regKeyApp.DisplayName -match 'Cumulative Update') { continue }
                if ($regKeyApp.DisplayName -match 'Security Update') { continue }
                if ($regKeyApp.DisplayName -match 'Hotfix') { continue }
            }

            ## Remove any control characters which may interfere with logging and creating file path names from these variables
            $appDisplayName = $regKeyApp.DisplayName -replace '[^\u001F-\u007F]',''
            $appDisplayVersion = $regKeyApp.DisplayVersion -replace '[^\u001F-\u007F]',''
            $appPublisher = $regKeyApp.Publisher -replace '[^\u001F-\u007F]',''

            ## Determine if application is a 64-bit application
            [boolean] $Is64BitApp = if (([System.Environment]::Is64BitOperatingSystem) -and ($regKeyApp.PSPath -notmatch '^Microsoft\.PowerShell\.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node')) { $true } else { $false }

            if ($PSCmdlet.ParameterSetName -eq 'ProductCode') {
                ## Verify if there is a match with the product code passed to the script
                if (($regKeyApp.PSChildName -as [guid]).Guid -eq ($ProductCode -as [guid]).Guid) {
                    Write-Information "[Get-InstalledApplication] Found installed application [$appDisplayName] version [$appDisplayVersion] matching product code [$productCode]."
                    $installedApplication.Add(@{
                        UninstallSubkey = $regKeyApp.PSChildName
                        ProductCode = $regKeyApp.PSChildName -as [guid]
                        DisplayName = $appDisplayName
                        DisplayVersion = $appDisplayVersion
                        UninstallString = $regKeyApp.UninstallString
                        QuietUninstallString = $regKeyApp.QuietUninstallString
                        InstallSource = $regKeyApp.InstallSource
                        InstallLocation = $regKeyApp.InstallLocation
                        InstallDate = $regKeyApp.InstallDate
                        Publisher = $appPublisher
                        Is64BitApplication = $Is64BitApp
                        PSPath = $regKeyApp.PSPath
                    }) | Out-Null
                }
            } else {
                ## Verify if there is a match with the application name(s) passed to the script
                foreach ($application in $Name) {
                    $applicationMatched = $false
                    if ($Exact.IsPresent) {
                        Write-Debug ('[Get-InstalledApplication] $Exact.IsPresent')
                        # Check for exact application name match
                        if ($CaseSensitive.IsPresent) {
                            # Check for a CaseSensitive application name match
                            if ($regKeyApp.DisplayName -ceq $application) {
                                $applicationMatched = $true
                                Write-Information "[Get-InstalledApplication] Found installed application [$appDisplayName] version [$appDisplayVersion] using casesensitive exact name matching for search term [$application]."
                            }
                        } elseif ($regKeyApp.DisplayName -eq $application) {
                            $applicationMatched = $true
                            Write-Information "[Get-InstalledApplication] Found installed application [$appDisplayName] version [$appDisplayVersion] using exact name matching for search term [$application]."
                        }
                    } elseif ($RegEx.IsPresent) {
                        Write-Debug ('[Get-InstalledApplication] $RegEx.IsPresent')
                        # Check for a regex application name match
                        if ($CaseSensitive.IsPresent) {
                            # Check for a CaseSensitive application name match
                            if ($regKeyApp.DisplayName -cmatch $application) {
                                $applicationMatched = $true
                                Write-Information "[Get-InstalledApplication] Found installed application [$appDisplayName] version [$appDisplayVersion] using casesensitive regex name matching for search term [$application]."
                            }
                        } elseif ($regKeyApp.DisplayName -match $application) {
                            $applicationMatched = $true
                            Write-Information "[Get-InstalledApplication] Found installed application [$appDisplayName] version [$appDisplayVersion] using regex name matching for search term [$application]."
                        }
                    } else {
                        # Check for a like application name match
                        if ($CaseSensitive.IsPresent) {
                            # Check for a CaseSensitive application name match
                            if ($regKeyApp.DisplayName -clike $application) {
                                $applicationMatched = $true
                                Write-Information "[Get-InstalledApplication] Found installed application [$appDisplayName] version [$appDisplayVersion] using casesensitive like name matching for search term [$application]."
                            } else {
                                Write-Information "[Get-InstalledApplication] No found installed application using casesensitive like name matching for search term [$application]."
                            }
                        } elseif ($regKeyApp.DisplayName -like $application) {
                            $applicationMatched = $true
                            Write-Information "[Get-InstalledApplication] Found installed application [$appDisplayName] version [$appDisplayVersion] using like name matching for search term [$application]."
                        }
                    }

                    if ($applicationMatched) {
                        $installedApplication.Add(@{
                            UninstallSubkey = $regKeyApp.PSChildName
                            ProductCode = $regKeyApp.PSChildName -as [guid]
                            DisplayName = $appDisplayName
                            DisplayVersion = $appDisplayVersion
                            UninstallString = $regKeyApp.UninstallString
                            QuietUninstallString = $regKeyApp.QuietUninstallString
                            InstallSource = $regKeyApp.InstallSource
                            InstallLocation = $regKeyApp.InstallLocation
                            InstallDate = $regKeyApp.InstallDate
                            Publisher = $appPublisher
                            Is64BitApplication = $Is64BitApp
                            PSPath = $regKeyApp.PSPath
                        }) | Out-Null
                    }
                }
            }
        } catch {
            Write-Error "[Get-InstalledApplication] Failed to resolve application details from registry for [$appDisplayName].$(if (Get-Command 'Resolve-Error' -ErrorAction 'Ignore') { "`n{0}" -f (Resolve-Error) })"
            continue
        }
    }

    Write-Information ('[Get-InstalledApplication] Application Searched: {0}' -f $application)
    return $installedApplication
}
<#
.SYNOPSIS
Get message for MSI error code
.DESCRIPTION
Get message for MSI error code by reading it from msimsg.dll
.PARAMETER MsiErrorCode
MSI error code
.PARAMETER MsiLog
MSI Log File. Parsed if ErrorCode is 1603.
.EXAMPLE
Get-MsiExitCodeMessage -MsiExitCode 1618
.NOTES
This is an internal script function and should typically not be called directly.
- https://learn.microsoft.com/en-us/previous-versions//aa368542(v=vs.85)
 
> Copyright â’¸ 2015 - PowerShell App Deployment Toolkit Team
>
> Copyright â’¸ 2023 - Raymond Piller (VertigoRay)
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-msiexitcodemessage
#>

function Get-MsiExitCodeMessage {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullorEmpty()]
        [int32]
        $MsiExitCode
        ,
        [Parameter(Mandatory=$false)]
        [ValidateNotNullorEmpty()]
        [string]
        $MsiLog
    )

    Write-Information "> $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
    Write-Debug "Function Invocation: $($MyInvocation | Out-String)"

    switch ($MsiExitCode) {
        # MsiExec.exe and InstMsi.exe Error Messages
        # https://msdn.microsoft.com/en-us/library/aa368542(v=vs.85).aspx
        1603 {
            $return = 'ERROR_INSTALL_FAILURE: A fatal error occurred during installation.'
            $return += "`nLook for `"return value 3`" in the MSI log file. The real cause of this error will be just before this line."

            if ($MsiLog) {
                $return += "`nImporting `"return value 3`" info from the MSI log, but you might still want to look at the MSI log:"
                $log_contents = Get-Content $MsiLog

                [System.Collections.ArrayList] $return_value_3_lines = @()
                foreach ($line in $log_contents) {
                    if ($line -ilike '*return value 3*') {
                        $return_value_3_lines.Add($line) | Out-Null
                    }
                }

                foreach ($return_value_3 in $return_value_3_lines) {
                    $i = $log_contents.IndexOf($return_value_3)

                    $return += "`n`t$(Split-Path $MsiLog -Leaf):$($i-1) : $($log_contents[$i-1])"
                    $return += "`n`t$(Split-Path $MsiLog -Leaf):$($i) : $($log_contents[$i])"
                }
            }
        }
        3010 {
            Write-Information "Standard Message: Restart required. The installation or update for the product required a restart for all changes to take effect. The restart was deferred to a later time."
            $return = (Get-Content $MsiLog)[-10..-1] | Where-Object { $_.Trim() -ne '' } | Out-String
        }
        default {
            $code = @'
                enum LoadLibraryFlags : int {
                    DONT_RESOLVE_DLL_REFERENCES = 0x00000001,
                    LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010,
                    LOAD_LIBRARY_AS_DATAFILE = 0x00000002,
                    LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040,
                    LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020,
                    LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008
                }
 
                [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = false)]
                static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, LoadLibraryFlags dwFlags);
 
                [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
                static extern int LoadString(IntPtr hInstance, int uID, StringBuilder lpBuffer, int nBufferMax);
 
                // Get MSI exit code message from msimsg.dll resource dll
                public static string GetMessageFromMsiExitCode(int errCode) {
                    IntPtr hModuleInstance = LoadLibraryEx("msimsg.dll", IntPtr.Zero, LoadLibraryFlags.LOAD_LIBRARY_AS_DATAFILE);
 
                    StringBuilder sb = new StringBuilder(255);
                    LoadString(hModuleInstance, errCode, sb, sb.Capacity + 1);
 
                    return sb.ToString();
                }
'@


            [string[]] $ReferencedAssemblies = 'System', 'System.IO', 'System.Reflection'
            try {
                Add-Type -Name 'MsiMsg' -MemberDefinition $code -ReferencedAssemblies $ReferencedAssemblies -UsingNamespace 'System.Text' -IgnoreWarnings -ErrorAction 'Stop'
            } catch [System.Exception] {
                # Add-Type : Cannot add type. The type name 'Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes.MsiMsg' already exists.
                Write-Warning $_
            }

            $return = [Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes.MsiMsg]::GetMessageFromMsiExitCode($MsiExitCode)
        }
    }

        Write-Information "Return: ${return}"
        return $return
}
<#
.SYNOPSIS
Get all of the properties from a Windows Installer database table or the Summary Information stream and return as a custom object.
.DESCRIPTION
Use the Windows Installer object to read all of the properties from a Windows Installer database table or the Summary Information stream.
.PARAMETER Path
The fully qualified path to an database file. Supports .msi and .msp files.
.PARAMETER TransformPath
The fully qualified path to a list of MST file(s) which should be applied to the MSI file.
.PARAMETER Table
The name of the the MSI table from which all of the properties must be retrieved. Default is: 'Property'.
.PARAMETER TablePropertyNameColumnNum
Specify the table column number which contains the name of the properties. Default is: 1 for MSIs and 2 for MSPs.
.PARAMETER TablePropertyValueColumnNum
Specify the table column number which contains the value of the properties. Default is: 2 for MSIs and 3 for MSPs.
.PARAMETER GetSummaryInformation
Retrieves the Summary Information for the Windows Installer database.
Summary Information property descriptions: https://msdn.microsoft.com/en-us/library/aa372049(v=vs.85).aspx
.PARAMETER ContinueOnError
Continue if an error is encountered. Default is: $true.
.EXAMPLE
# Retrieve all of the properties from the default 'Property' table.
Get-MsiTableProperty -Path 'C:\Package\AppDeploy.msi' -TransformPath 'C:\Package\AppDeploy.mst'
Get-MsiTableProperty -Path 'C:\Package\AppDeploy.msi' -TransformPath 'C:\Package\AppDeploy.mst'
.EXAMPLE
# Retrieve all of the properties from the 'Property' table and then pipe to Select-Object to select the ProductCode property.
Get-MsiTableProperty -Path 'C:\Package\AppDeploy.msi' -TransformPath 'C:\Package\AppDeploy.mst' -Table 'Property' | Select-Object -ExpandProperty ProductCode
Get-MsiTableProperty -Path 'C:\Package\AppDeploy.msi' -TransformPath 'C:\Package\AppDeploy.mst' -Table 'Property' | Select-Object -ExpandProperty ProductCode
.EXAMPLE
# Retrieves the Summary Information for the Windows Installer database.
Get-MsiTableProperty -Path 'C:\Package\AppDeploy.msi' -GetSummaryInformation
Get-MsiTableProperty -Path 'C:\Package\AppDeploy.msi' -GetSummaryInformation
.NOTES
This is an internal script function and should typically not be called directly.
 
> Copyright â’¸ 2015 - PowerShell App Deployment Toolkit Team
>
> Copyright â’¸ 2023 - Raymond Piller (VertigoRay)
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-msitableproperty
#>

function Get-MsiTableProperty {
    [CmdletBinding(DefaultParameterSetName='TableInfo')]
    Param (
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateScript({ Test-Path -LiteralPath $_ -PathType 'Leaf' })]
        [string]
        $Path
        ,
        [Parameter(Mandatory=$false)]
        [ValidateScript({ Test-Path -LiteralPath $_ -PathType 'Leaf' })]
        [string[]]
        $TransformPath
        ,
        [Parameter(Mandatory=$false,ParameterSetName='TableInfo')]
        [ValidateNotNullOrEmpty()]
        [string]
        $Table = $(if ([IO.Path]::GetExtension($Path) -eq '.msi') { 'Property' } else { 'MsiPatchMetadata' })
        ,
        [Parameter(Mandatory=$false,ParameterSetName='TableInfo')]
        [ValidateNotNullorEmpty()]
        [int32]
        $TablePropertyNameColumnNum = $(if ([IO.Path]::GetExtension($Path) -eq '.msi') { 1 } else { 2 })
        ,
        [Parameter(Mandatory=$false,ParameterSetName='TableInfo')]
        [ValidateNotNullorEmpty()]
        [int32]
        $TablePropertyValueColumnNum = $(if ([IO.Path]::GetExtension($Path) -eq '.msi') { 2 } else { 3 })
        ,
        [Parameter(Mandatory=$false,ParameterSetName='SummaryInfo')]
        [ValidateNotNullorEmpty()]
        [switch]
        $GetSummaryInformation = $false
        ,
        [Parameter(Mandatory=$false)]
        [ValidateNotNullorEmpty()]
        [boolean]
        $ContinueOnError = $true
    )

    Begin {
        <#
        .SYNOPSIS
        Get a property from any object.
        .DESCRIPTION
        Get a property from any object.
        .PARAMETER InputObject
        Specifies an object which has properties that can be retrieved.
        .PARAMETER PropertyName
        Specifies the name of a property to retrieve.
        .PARAMETER ArgumentList
        Argument to pass to the property being retrieved.
        .EXAMPLE
        Get-ObjectProperty -InputObject $Record -PropertyName 'StringData' -ArgumentList @(1)
        .NOTES
        This is an internal script function and should typically not be called directly.
        .LINK
        https://psappdeploytoolkit.com
        #>

        function Private:Get-ObjectProperty {
            [CmdletBinding()]
            Param (
                [Parameter(Mandatory=$true,Position=0)]
                [ValidateNotNull()]
                [object]$InputObject,
                [Parameter(Mandatory=$true,Position=1)]
                [ValidateNotNullorEmpty()]
                [string]$PropertyName,
                [Parameter(Mandatory=$false,Position=2)]
                [object[]]$ArgumentList
            )

            Begin { }
            Process {
                ## Retrieve property
                Write-Output -InputObject $InputObject.GetType().InvokeMember($PropertyName, [Reflection.BindingFlags]::GetProperty, $null, $InputObject, $ArgumentList, $null, $null, $null)
            }
            End { }
        }
    }



    Process {
        try {
            if ($PSCmdlet.ParameterSetName -eq 'TableInfo') {
                Write-Information "Read data from Windows Installer database file [${Path}] in table [${Table}]."
            } else {
                Write-Information "Read the Summary Information from the Windows Installer database file [${Path}]."
            }

            ## Create a Windows Installer object
            [__comobject]$Installer = New-Object -ComObject 'WindowsInstaller.Installer' -ErrorAction 'Stop'
            ## Determine if the database file is a patch (.msp) or not
            if ([IO.Path]::GetExtension($Path) -eq '.msp') { [boolean]$IsMspFile = $true }
            ## Define properties for how the MSI database is opened
            [int32]$msiOpenDatabaseModeReadOnly = 0
            [int32]$msiSuppressApplyTransformErrors = 63
            [int32]$msiOpenDatabaseMode = $msiOpenDatabaseModeReadOnly
            [int32]$msiOpenDatabaseModePatchFile = 32
            if ($IsMspFile) { [int32]$msiOpenDatabaseMode = $msiOpenDatabaseModePatchFile }
            ## Open database in read only mode
            [__comobject]$Database = Invoke-ObjectMethod -InputObject $Installer -MethodName 'OpenDatabase' -ArgumentList @($Path, $msiOpenDatabaseMode)
            ## Apply a list of transform(s) to the database
            if (($TransformPath) -and (-not $IsMspFile)) {
                foreach ($Transform in $TransformPath) {
                    $null = Invoke-ObjectMethod -InputObject $Database -MethodName 'ApplyTransform' -ArgumentList @($Transform, $msiSuppressApplyTransformErrors)
                }
            }

            ## Get either the requested windows database table information or summary information
            if ($PSCmdlet.ParameterSetName -eq 'TableInfo') {
                ## Open the requested table view from the database
                [__comobject]$View = Invoke-ObjectMethod -InputObject $Database -MethodName 'OpenView' -ArgumentList @("SELECT * FROM ${Table}")
                $null = Invoke-ObjectMethod -InputObject $View -MethodName 'Execute'

                ## Create an empty object to store properties in
                [psobject]$TableProperties = New-Object -TypeName 'PSObject'

                ## Retrieve the first row from the requested table. if the first row was successfully retrieved, then save data and loop through the entire table.
                # https://msdn.microsoft.com/en-us/library/windows/desktop/aa371136(v=vs.85).aspx
                [__comobject]$Record = Invoke-ObjectMethod -InputObject $View -MethodName 'Fetch'
                while ($Record) {
                    # Read string data from record and add property/value pair to custom object
                    $TableProperties | Add-Member -MemberType 'NoteProperty' -Name (Get-ObjectProperty -InputObject $Record -PropertyName 'StringData' -ArgumentList @($TablePropertyNameColumnNum)) -Value (Get-ObjectProperty -InputObject $Record -PropertyName 'StringData' -ArgumentList @($TablePropertyValueColumnNum)) -Force
                    # Retrieve the next row in the table
                    [__comobject]$Record = Invoke-ObjectMethod -InputObject $View -MethodName 'Fetch'
                }
                Write-Output -InputObject $TableProperties
            } else {
                ## Get the SummaryInformation from the windows installer database
                [__comobject]$SummaryInformation = Get-ObjectProperty -InputObject $Database -PropertyName 'SummaryInformation'
                [hashtable]$SummaryInfoProperty = @{}
                ## Summary property descriptions: https://msdn.microsoft.com/en-us/library/aa372049(v=vs.85).aspx
                $SummaryInfoProperty.Add('CodePage', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(1)))
                $SummaryInfoProperty.Add('Title', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(2)))
                $SummaryInfoProperty.Add('Subject', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(3)))
                $SummaryInfoProperty.Add('Author', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(4)))
                $SummaryInfoProperty.Add('Keywords', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(5)))
                $SummaryInfoProperty.Add('Comments', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(6)))
                $SummaryInfoProperty.Add('Template', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(7)))
                $SummaryInfoProperty.Add('LastSavedBy', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(8)))
                $SummaryInfoProperty.Add('RevisionNumber', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(9)))
                $SummaryInfoProperty.Add('LastPrinted', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(11)))
                $SummaryInfoProperty.Add('CreateTimeDate', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(12)))
                $SummaryInfoProperty.Add('LastSaveTimeDate', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(13)))
                $SummaryInfoProperty.Add('PageCount', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(14)))
                $SummaryInfoProperty.Add('WordCount', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(15)))
                $SummaryInfoProperty.Add('CharacterCount', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(16)))
                $SummaryInfoProperty.Add('CreatingApplication', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(18)))
                $SummaryInfoProperty.Add('Security', (Get-ObjectProperty -InputObject $SummaryInformation -PropertyName 'Property' -ArgumentList @(19)))
                [psobject]$SummaryInfoProperties = New-Object -TypeName 'PSObject' -Property $SummaryInfoProperty
                Write-Output -InputObject $SummaryInfoProperties
            }
        } catch {
            $resolvedError = if (Get-Command 'Resolve-Error' -ErrorAction 'Ignore') { Resolve-Error } else { $null }
            Write-Error ('Failed to get the MSI table [{0}]. {1}' -f $Table, $resolvedError)
            if (-not $ContinueOnError) {
                throw ('Failed to get the MSI table [{0}]. {1}' -f $Table, $_.Exception.Message)
            }
        }
        finally {
            try {
                if ($View) {
                    $null = Invoke-ObjectMethod -InputObject $View -MethodName 'Close' -ArgumentList @()
                    try {
                        $null = [Runtime.Interopservices.Marshal]::ReleaseComObject($View)
                    } catch {
                        Write-Verbose ('[Get-MsiTableProperty] Unexpected Non-Fatal Error: {0}' -f $_)
                    }
                } elseif ($SummaryInformation) {
                    try {
                        $null = [Runtime.Interopservices.Marshal]::ReleaseComObject($SummaryInformation)
                    } catch {
                        Write-Verbose ('[Get-MsiTableProperty] Unexpected Non-Fatal Error: {0}' -f $_)
                    }
                }
            } catch {
                Write-Verbose ('[Get-MsiTableProperty] Unexpected Non-Fatal Error: {0}' -f $_)
            }
            try {
                $null = [Runtime.Interopservices.Marshal]::ReleaseComObject($DataBase)
            } catch {
                Write-Verbose ('[Get-MsiTableProperty] Unexpected Non-Fatal Error: {0}' -f $_)
            }
            try {
                $null = [Runtime.Interopservices.Marshal]::ReleaseComObject($Installer)
            } catch {
                Write-Verbose ('[Get-MsiTableProperty] Unexpected Non-Fatal Error: {0}' -f $_)
            }
        }
    }

    End {}
}
<#
.SYNOPSIS
Recursively probe registry key's sub-key's and values and output a sorted array.
.DESCRIPTION
Recursively probe registry key's sub-key's and values and output a sorted array.
.PARAMETER Key
This is the key path within the hive. Do not include the Hive itself.
.PARAMETER Hive
This is a top-level node in the registry as defined by [RegistryHive Enum](https://learn.microsoft.com/en-us/dotnet/api/microsoft.win32.registryhive).
.EXAMPLE
Get-RecursiveRegistryKey 'SOFTWARE\Palo Alto Networks\GlobalProtect'
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-registrykeyasarray
#>

function Get-RegistryKeyAsArray([string] $Key, [string] $Hive = 'LocalMachine') {
    #region Parameter Validation
    $hives = @(
        'ClassesRoot'
        'CurrentConfig'
        'CurrentUser'
        'LocalMachine'
        'PerformanceData'
        'Users'
    )
    if ($hives -notcontains $Hive) {
        throw [System.Management.Automation.ItemNotFoundException] ('Provided hive ({0}) should be one of: {1}.' -f $hive, ($hives -join ', '))
    }
    #endregion Parameter Validation

    # Declare an arraylist to which the recursive function below can append values.
    [System.Collections.ArrayList] $RegKeysArray = 'KeyName', 'ValueName', 'Value'

    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $ComputerName)
    $RegKey= $Reg.OpenSubKey($RegPath)

    function DigThroughKeys([Microsoft.Win32.RegistryKey] $Key) {
        # If it has no subkeys, retrieve the values and append to them to the global array.
        if ($Key.SubKeyCount-eq 0) {
            foreach ($value in $Key.GetValueNames()) {
                if ($null -ne $Key.GetValue($value)) {
                    [void] $RegKeysArray.Add(([PSObject] @{
                        KeyName = $Key.Name
                        ValueName = $value.ToString()
                        Value = $Key.GetValue($value)
                    }))
                }
            }
        } else {
            if ($Key.ValueCount -gt 0) {
                foreach ($value in $Key.GetValueNames()) {
                    if ($null -ne $Key.GetValue($value)) {
                        [void] $RegKeysArray.Add(([PSObject] @{
                            KeyName = $Key.Name
                            ValueName = $value.ToString()
                            Value = $Key.GetValue($value)
                        }))
                    }
                }
            }
            #Recursive lookup happens here. If the key has subkeys, send the key(s) back to this same function.
            if ($Key.SubKeyCount -gt 0) {
                foreach ($subKey in $Key.GetSubKeyNames()) {
                    DigThroughKeys -Key $Key.OpenSubKey($subKey)
                }
            }
        }
    }

    DigThroughKeys -Key $RegKey

    #Write the output to the console.
    Write-Output ($RegKeysArray | Select-Object KeyName, ValueName, Value | Sort-Object ValueName | Format-Table)

    $Reg.Close()
}
<#
.SYNOPSIS
Get the values in a registry key and all sub-keys.
.DESCRIPTION
Get the values in a registry key and all sub-keys.
This shouldn't be used to pull a massive section of the registry expecting perfect results.
 
There's a fundamental flaw that I'm unsure how to address with a hashtable.
If there's a value and sub-key with the same name at the same key level, the sub-key won't be processed.
Because of this, use this function to only return key sections with known/expected structures.
Otherwise, consider using [Get-RedstoneRegistryKeyAsArray](https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-registrykeyasarray).
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-registrykeyashashtable
#>

function Get-RegistryKeyAsHashtable ([string] $Key, [switch] $Recurse) {
    $private:hash = @{}

    if (Test-Path $Key) {
        $values = (Get-Item $Key).Property
        foreach ($value in (Get-ItemProperty $Key).PSObject.Properties) {
            if ($value.Name -in $values) {
                $private:hash.Add($value.Name, $value.Value)
            }
        }

        if ($Recurse) {
            foreach ($item in (Get-ChildItem $Key -ErrorAction 'Ignore')) {
                if ($private:hash.Keys -notcontains $item.PSChildName) {
                    $private:hash.Add($item.PSChildName, (Get-RegistryKeyAsHashtable -Key $item.PSPath))
                }
            }
        }
    }

    return $private:hash
}
<#
.SYNOPSIS
Get a registry value without expanding environment variables.
.OUTPUTS
[bool]
.EXAMPLE
Get-RegistryValueDoNotExpandEnvironmentName 'HKCU:\Thing Foo'
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-registryvaluedonotexpandenvironmentname
#>

function Get-RegistryValueDoNotExpandEnvironmentName {
    [OutputType([bool])]
    [CmdletBinding()]
    Param(
        [Parameter()]
        [string]
        $Key,

        [Parameter()]
        [string]
        $Value
    )

    Write-Verbose ('[Get-RegistryValueDoNotExpandEnvironmentName] >')
    Write-Debug ('[Get-RegistryValueDoNotExpandEnvironmentName] > {0}' -f ($MyInvocation | Out-String))

    $item = Get-Item $Key
    if ($item) {
        return $item.GetValue($Value, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
    } else {
        return $null
    }
}
<#
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-registryvalueordefault
#>

function Get-RegistryValueOrDefault {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [string]
        $RegistryKey,

        [Parameter(Mandatory = $true, Position = 1)]
        [string]
        $RegistryValue,

        [Parameter(Mandatory = $true, Position = 2)]
        $DefaultData,

        [Parameter(Mandatory = $false)]
        [string]
        $RegistryKeyRoot,

        [Parameter(HelpMessage = 'Do Not Expand Environment Variables.')]
        [switch]
        $DoNotExpand,

        [Parameter(HelpMessage = 'For development.')]
        [bool]
        $OnlyUseDefaultSettings
    )

    Write-Verbose "[Get-RegistryValueOrDefault] > $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
    Write-Debug "[Get-RegistryValueOrDefault] Function Invocation: $($MyInvocation | Out-String)"

    if ($OnlyUseDefaultSettings) {
        Write-Verbose "[Get-RegistryValueOrDefault] OnlyUseDefaultSettings Set; Returning: ${DefaultValue}"
        return $DefaultData
    }

    if ($RegistryKeyRoot -as [bool]) {
        $RegistryDrives = (Get-PSDrive -PSProvider 'Registry').Name + 'Registry:' | ForEach-Object { '{0}:' -f $_ }
        if ($RegistryKey -notmatch ($RegistryDrives -join '|')) {
            $RegistryKey = Join-Path $RegistryKeyRoot $RegistryKey
            Write-Debug "[Get-RegistryValueOrDefault] RegistryKey adjusted to: ${RegistryKey}"
        }
    }

    try {
        if ($DoNotExpand.IsPresent) {
            $result = Get-RegistryValueDoNotExpandEnvironmentName -Key $RegistryKey -Value $RegistryValue
            Write-Verbose "[Get-RegistryValueOrDefault] Registry Set; Returning: ${result}"
        } else {
            $result = Get-ItemPropertyValue -Path $RegistryKey -Name $RegistryValue -ErrorAction 'Stop'
            Write-Verbose "[Get-RegistryValueOrDefault] Registry Set; Returning: ${result}"
        }
        return $result
    } catch [System.Management.Automation.PSArgumentException] {
        Write-Verbose "[Get-RegistryValueOrDefault] Registry Not Set; Returning Default: ${DefaultValue}"
        if ($Error) { $Error.RemoveAt(0) } # This isn't a real error, so I don't want it in the error record.
        return $DefaultData
    } catch [System.Management.Automation.ItemNotFoundException] {
        Write-Verbose "[Get-RegistryValueOrDefault] Registry Not Set; Returning Default: ${DefaultValue}"
        if ($Error) { $Error.RemoveAt(0) } # This isn't a real error, so I don't want it in the error record.
        return $DefaultData
    }
}
<#
.NOTES
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.win32exception
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#get-translatederrorcode
#>

function Get-TranslatedErrorCode {
    [CmdletBinding()]
    [OutputType([System.ComponentModel.Win32Exception])]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [ComponentModel.Win32Exception]
        $ErrorCode,

        [Parameter(Mandatory = $false)]
        [switch]
        $MECM
    )

    Write-Verbose ('[Get-TranslatedErrorCode] >')
    Write-Debug ('[Get-TranslatedErrorCode] > {0}' -f ($MyInvocation | Out-String))

    # Write-Host ($ErrorCode | Select-Object '*' | Out-String) -ForegroundColor Cyan

    $srsResourcesGetErrorMessage = {
        param([ComponentModel.Win32Exception] $ErrorCode)

        $dllSrsResources = [IO.Path]::Combine(([IO.DirectoryInfo] $env:SMS_ADMIN_UI_PATH).Parent.FullName, 'SrsResources.dll')
        [void] [System.Reflection.Assembly]::LoadFrom($dllSrsResources)

        $result = @{
            ErrorCode = $ErrorCode.NativeErrorCode
            Message = [SrsResources.Localization]::GetErrorMessage($ErrorCode.NativeErrorCode, (Get-Culture).Name)
        }
        if ($result.Message.StartsWith('Unknown error (') -or $result.Message.StartsWith('Unspecified error')) {
            $result = @{
                ErrorCode = $ErrorCode.ErrorCode
                Message = [SrsResources.Localization]::GetErrorMessage($ErrorCode.ErrorCode, (Get-Culture).Name)
            }
        }

        if ($result.Message.StartsWith('Unknown error (') -or $result.Message.StartsWith('Unspecified error')) {
            # If nothing at all could be found, send back original error object.
            return $ErrorCode
        }
        # If we found something, send back what we found.
        return ([PSObject]  $result)
    }

    if ($MECM.IsPresent -and $env:SMS_ADMIN_UI_PATH) {
        $result = & $srsResourcesGetErrorMessage -ErrorCode $ErrorCode
    } elseif ($MECM.IsPresent) {
        Throw [System.Management.Automation.ItemNotFoundException] ('Environment Variable Expected: SMS_ADMIN_UI_PATH (https://learn.microsoft.com/en-us/powershell/sccm/overview?view=sccm-ps)')
    } else {
        $result = $ErrorCode
    }

    if ($result.Message.StartsWith('Unknown error (') -and $env:SMS_ADMIN_UI_PATH) {
        # Let's try looking it up as a MECM error
        $result = & $srsResourcesGetErrorMessage -ErrorCode $ErrorCode
    }

    if ($result.Message.StartsWith('Unknown error (')) {
        # Let's define some unknown errors the best we can ...
        switch ($result.ErrorCode) {
            -1073741728 {
                # https://errorco.de/win32/ntstatus-h/status_no_such_privilege/-1073741728/
                return ([PSObject] @{
                    ErrorCode = $result.ErrorCode
                    Message = 'A required privilege is not held by the client. (STATUS_PRIVILEGE_NOT_HELD 0x{0:x})' -f $result.ErrorCode
                })
            }
            default {
                return $result
            }
        }
    } else {
        return $ErrorCode
    }
}
<#
.SYNOPSIS
Simplify the looping through user profiles and user registries.
.DESCRIPTION
Simplify the looping through user profiles and user registries by calling this function that gets what you need quickly.
 
Each user profile that is returned will contain information in the following hashtable:
 
```powershell
@{
    Domain = 'CONTOSO'
    Username = 'jsmith'
    Path = [IO.DirectoryInfo] 'C:\Users\jsmith'
    SID = 'S-1-5-21-1111111111-2222222222-3333333333-123456'
    RegistryKey = [Microsoft.Win32.RegistryKey] 'HKEY_USERS\S-1-5-21-1111111111-2222222222-3333333333-123456'
}
```
.PARAMETER Redstone
Provide the redstone class variable so we don't have to create a new one for you.
.PARAMETER AllProfiles
Include all user profiles, including service accounts.
Otherwise just [S-1-5-21 User Accounts](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers#security-identifier-architecture) would be included.
.PARAMETER AddDefaultUser
Include the default User.
Keep in mind, no Domain or SID information will be provided for the default user, and the username will be `DEFAULT`.
.PARAMETER IncludeUserRegistryKey
Include the path to each user hive (aka HKCU).
 
If `AddDefaultUser` was provided, the hive will be mounted and requires special considertion.
You should use [`Set-RedstoneRegistryHiveItemProperty`](https://github.com/VertigoRay/PSRedstone/wiki/Functions#set-redstoneregistryhiveitemproperty) to make changes to mounted hives.
The [`Dismount-RedstoneRegistryHive`](https://github.com/VertigoRay/PSRedstone/wiki/Functions#dismount-redstoneregistryhive) is registered to the `PowerShell.Exiting` event for you by the [`Mount-RedstoneRegistryHive`](https://github.com/VertigoRay/PSRedstone/wiki/Functions#mount-redstoneregistryhive) function.
.PARAMETER DomainSid
Filter for the provided Sid.
If an `*` is not included at the end, it will be added.
.PARAMETER NotDomainSid
Filter out the provided Sid.
If an `*` is not included at the end, it will be added.
.EXAMPLE
foreach ($profilePath in (Get-UserProfiles)) { $profilePath }
#>

function Get-UserProfiles ([Redstone] $Redstone, [switch] $AllProfiles, [string] $DomainSid = $null, [string] $NotDomainSid = $null, [switch] $AddDefaultUser, [switch] $IncludeUserRegKey) {
    if (-not $Redstone) {
        try {
            $Redstone, $null = New-Redstone
        } catch {
            Throw [System.Management.Automation.ItemNotFoundException] ('Unable to find or create a redstone class. If your Redstone class is not stored on the variable `$redstone` then you must provide it in the `-Redstone` parameter. Tried making you a redstone class, but got this instantiation error: {0}' -f $_)
        }
    }

    $profiles = $Redstone.ProfileList.Profiles

    if (-not $AllProfiles.IsPresent) {
        # filter down to only user accounts
        $profiles = $profiles | Where-Object { $_.SID.StartsWith('S-1-5-21-') }
    }

    if ($DomainSid.IsPresent) {
        $DomainSid = '{0}*' -f $DomainSid.TrimEnd('*')
        $profiles = $profiles | Where-Object { $_.SID -like $DomainSid }
    }

    if ($NotDomainSid.IsPresent) {
        $NotDomainSid = '{0}*' -f $NotDomainSid.TrimEnd('*')
        $profiles = $profiles | Where-Object { $_.SID -notlike $NotDomainSid }
    }

    if ($AddDefaultUser.IsPresent) {
        $profiles = $profiles + @(@{
            Domain = $null
            Username = 'DEFAULT'
            Path = $Redstone.ProfileList.Default
            SID = $null
        })
    }

    if ($IncludeUserRegistryKey.IsPresent) {
        $profiles = foreach ($profile in $profiles) {
            if ($profile.Username -eq 'DEFAULT') {
                $hive = Mount-RegistryHive -DefaultUser
                $profile.Add('RegistryKey', $hive)
            } elseif ($profile.SID) {
                $profile.Add('RegistryKey', (Get-Item ('Registry::HKEY_USERS\{0}' -f $profile.SID) -ErrorAction 'Ignore'))
            }

            Write-Output $profile
        }
    }

    return $profiles.GetEnumerator()
}
<#
.SYNOPSIS
This is an advanced function for scheduling the install and reboot Windows Updates.
It utilizes and augments functionality provided by [PSWindowsUpdate](https://www.powershellgallery.com/packages/PSWindowsUpdate).
.DESCRIPTION
This advanced function for installing Windows Updates will try to fix Windows Updates, if desired, and fail back to non-PowerShell mechanisms for forcing Windows Updates.
It utilizes and augments functionality provided by [PSWindowsUpdate](https://www.powershellgallery.com/packages/PSWindowsUpdate).
 
If you want PSWindowsUpdate to send a report, you can use [PSDefaultParameterValues](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parameters_default_values?view=powershell-5.1) to make that happen:
 
```powershell
$PSDefaultParameterValues.Set_Item('Install-WindowsUpdate:SendReport', $true)
$PSDefaultParameterValues.Set_Item('Install-WindowsUpdate:SendHistory', $true)
$PSDefaultParameterValues.Set_Item('Install-WindowsUpdate:PSWUSettings', @{
    SmtpServer = 'smtp.sendgrid.net'
    Port = 465
    UseSsl = $true
    From = '{1} <{0}@mailinator.com>' -f (& HOSTNAME.EXE), $env:ComputerName
    To = 'PSRedstone@mailinator.com'
})
```
.PARAMETER LastDeploymentChangeThresholdDays
When using `PSWindowsUpdate`, this will check the `LastDeploymentChangeTime` and install updates past the threshold.
.PARAMETER ScheduleJob
Schedule with a valid `[datetime]` value.
I suggest using `Get-Date -Format O` to get a convertable string.
 
```powershell
$scheduleJob = (Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-7) | Get-Date -Format 'O' # 5pm today
```
.PARAMETER ScheduleReboot
Schedule with a valid `[datetime]` value.
I suggest using `Get-Date -Format O` to get a convertable string.
 
```powershell
$scheduleReboot = (Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-1) | Get-Date -Format 'O' # 11pm today
```
.PARAMETER NoPSWindowsUpdate
Do NOT install the PSWindowsUpdate module.
When this option is used, none of the advanced scheduling or reporting options are available.
.PARAMETER ToastNotification
If this parameter is not provided, not Toast Notification will be shown.
A hashtable used to [splat](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-5.1) into the PSRedstone Show-ToastNotification function.
 
The `ToastText` parameter will be [formatted](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-5.1#format-operator--f) with:
 
0. `$updateCount`
1. `$ToastNotification.ToastTextFormatters[0][$updateCount -gt 1]`
2. `$ToastNotification.ToastTextFormatters[1][$updateCount -gt 1]`
3. `$ToastNotification.ToastTextFormatters[2][$ScheduleJob -as [bool]]`
4. `$ToastNotification.ToastTextFormatters[3][$ScheduleReboot -as [bool]]`
 
Here's an example:
 
```powershell
$lastDeploymentChangeThresholdDays = 30
$scheduleJob = (Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-7) | Get-Date -Format 'O' # 5pm today
$scheduleReboot = (Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-1) | Get-Date -Format 'O' # 11pm today
 
$toastNotification = @{
    ToastNotifier = 'Tech Solutions: Endpoint Solutions Engineering'
    ToastTitle = 'Windows Update'
    ToastText = 'This computer is at least 30 days overdue for {0} Windows Update{1}. {2} being forced on your system {3}. A reboot may occur {4}.'
    ToastTextFormatters = @(
        @($null, 's')
        @('The update is', 'Updates are')
        @(('on {0}' -f ($scheduleJob | Get-Date -Format (Get-Culture).DateTimeFormat.FullDateTimePattern)), 'now')
        @(('on {0}' -f ($scheduleReboot | Get-Date -Format (Get-Culture).DateTimeFormat.FullDateTimePattern)), 'immediately afterwards')
    )
}
```
 
When `$toastNotification` is passed to this function, and there are five Windows Updates past due, it will result in a Toast Notification like this:
 
> `Tech Solutions: Endpoint Solutions Engineering`
>
> # Windows Update
>
> This computer is at least 30 days overdue for 5 Windows Updates. Updates are being forced on your system on Saturday, February 11, 2023 5:00:00 PM. Reboot will occur on Saturday, February 11, 2023 11:00:00 PM.
.PARAMETER FixWUAU
Attempt to fix the WUAU service.
.EXAMPLE
Install-WindowsUpdateAdv
 
This will install all available updates now and restart now.
.EXAMPLE
Install-WindowsUpdateAdv -FixWUAU
 
This will attempt to fix the WUAU service, install all available updates now, and restart immediately afterwards.
.EXAMPLE
Install-WindowsUpdateAdv -LastDeploymentChangeThresholdDays 30 -FixWUAU
 
This will attempt to fix the WUAU service, install all available updates now that are more than 30 days old, and restart immediately afterwards.
.EXAMPLE
Install-WindowsUpdateAdv -LastDeploymentChangeThresholdDays 30 -FixWUAU -ScheduleJob ((Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-7) | Get-Date -Format 'O')
 
This will attempt to fix the WUAU service now, install all available updates today at 5 pm that are more than 30 days old, and restart immediately afterwards.
.EXAMPLE
Install-WindowsUpdateAdv -LastDeploymentChangeThresholdDays 30 -FixWUAU -ScheduleJob ((Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-7) | Get-Date -Format 'O') -ScheduleReboot ((Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-1) | Get-Date -Format 'O')
 
This will attempt to fix the WUAU service now, install all available updates today at 5 pm that are more than 30 days old, and restart today at 11 pm.
.EXAMPLE
Install-WindowsUpdateAdv -LastDeploymentChangeThresholdDays 30 -FixWUAU -ScheduleJob $scheduleJob -ScheduleReboot $scheduleReboot -ToastNotification $toastNotification
 
This will show a toast notification for any logged on users, attempt to fix the WUAU service now, install all available updates today at 5 pm that are more than 30 days old, and restart today at 11 pm. The variables were defined like this:
 
```powershell
$scheduleJob = (Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-7) | Get-Date -Format 'O' # 5pm today
$scheduleReboot = (Get-Date -Format 'MM-dd-yyyy' | Get-Date).AddDays(1).AddHours(-1) | Get-Date -Format 'O' # 11pm today
 
$toastNotification = @{
    ToastNotifier = 'Tech Solutions: Endpoint Solutions Engineering'
    ToastTitle = 'Windows Update'
    ToastText = 'This computer is at least 30 days overdue for {0} Windows Update{1}. {2} being forced on your system {3}. A reboot may occur {4}.'
    ToastTextFormatters = @(
        @($null, 's')
        @('The update is', 'Updates are')
        @(('on {0}' -f ($scheduleJob | Get-Date -Format (Get-Culture).DateTimeFormat.FullDateTimePattern)), 'now')
        @(('on {0}' -f ($scheduleReboot | Get-Date -Format (Get-Culture).DateTimeFormat.FullDateTimePattern)), 'immediately afterwards')
    )
}
```
.EXAMPLE
Install-WindowsUpdateAdv -FixWUAU -NoPSWindowsUpdate
 
This will attempt to fix the WUAU service, install all available updates now, and restart immediately afterwards.
.NOTES
#>

function Install-WindowsUpdateAdv {
    [CmdletBinding(DefaultParameterSetName = 'PSWindowsUpdate')]
    param(
        [Parameter(HelpMessage = 'When using PSWindowsUpdate, this will check the LastDeploymentChangeTime and install updates past the threshold.', ParameterSetName = 'PSWindowsUpdate')]
        [int]
        $LastDeploymentChangeThresholdDays,

        [Parameter(HelpMessage = 'Schedule with a valid datetime value. I suggest using `Get-Date -Format O` to get a convertable string.', ParameterSetName = 'PSWindowsUpdate')]
        [datetime]
        $ScheduleJob,

        [Parameter(HelpMessage = 'Schedule with a valid datetime value. I suggest using `Get-Date -Format O` to get a convertable string.', ParameterSetName = 'PSWindowsUpdate')]
        [datetime]
        $ScheduleReboot,

        [Parameter(HelpMessage = 'Do NOT install the PSWindowsUpdate module.', ParameterSetName = 'NoPSWindowsUpdate')]
        [switch]
        $NoPSWindowsUpdate,

        [Parameter(HelpMessage = 'Parameters for Show-ToastNotification, if a toast notification is desired.', ParameterSetName = 'PSWindowsUpdate')]
        [Parameter(HelpMessage = 'Parameters for Show-ToastNotification, if a toast notification is desired.', ParameterSetName = 'NoPSWindowsUpdate')]
        [hashtable]
        $ToastNotification,

        [Parameter(HelpMessage = 'Attempt to fix the WUAU service.', ParameterSetName = 'PSWindowsUpdate')]
        [Parameter(HelpMessage = 'Attempt to fix the WUAU service.', ParameterSetName = 'NoPSWindowsUpdate')]
        [switch]
        $FixWUAU
    )

    if (($PSVersionTable.PSVersion -ge '5.1')) {
        if (-not $NoPSWindowsUpdate.IsPresent) {
            [version] $nugetPPMinVersion = '2.8.5.201'
            if (-not (Get-PackageProvider -Name 'NuGet' -ErrorAction 'Ignore' | Where-Object { $_.Version -ge $nugetPPMinVersion })) {
                Install-PackageProvider -Name 'NuGet' -MinimumVersion $nugetPPMinVersion -Force | Out-Null
            }
            [version] $psWindowsUpdateMinVersion = '2.2.0.3'
            if (-not (Get-Module -Name 'PSWindowsUpdate' -ErrorAction 'Ignore' | Where-Object { $_.Version -ge $psWindowsUpdateMinVersion })) {
                Install-Module -Name 'PSWindowsUpdate' -Scope 'CurrentUser' -MinimumVersion $psWindowsUpdateMinVersion -Confirm:$false -Force -ErrorAction Ignore | Out-Null
            }
        }

        $updates = Get-WindowsUpdate
        if ($MyInvocation.BoundParameters.Keys -contains 'LastDeploymentChangeThresholdDays') {
            $updates | Where-Object { $_.LastDeploymentChangeTime -lt (Get-Date).AddDays(-$LastDeploymentChangeThresholdDays) }
        }
        $updateCount = ($updates | Measure-Object).Count
        if ($updateCount -eq 0) {
            Write-Verbose '[Install-WindowsUpdate] Update Count: 0'
            return $updates
        } else {
            Write-Output ('[Install-WindowsUpdate] Update Count: {0}' -f $updateCount)
        }

        if ($ToastNotification) {
            $toastNotification  = @{
                ToastNotifier = 'Tech Solutions: Endpoint Solutions Engineering'
                ToastTitle = 'Windows Update'
                ToastText =  'This computer is overdue for {0} Windows Update{1} and the time threshold has exceeded. {2} being forced on your system {3}.{4}' -f @(
                    $updateCount
                    $ToastNotification.ToastTextFormatters[0][$updateCount -gt 1]
                    $ToastNotification.ToastTextFormatters[1][$updateCount -gt 1]
                    $ToastNotification.ToastTextFormatters[2][$ScheduleJob -as [bool]]
                    $ToastNotification.ToastTextFormatters[3][$ScheduleReboot -as [bool]]
                )
            }
            $ToastNotification.Remove('ToastTextFormatters')

            Show-ToastNotification @toastNotification
        }
    }

    if ($FixWUAU.IsPresent) {
        Stop-Service -Name 'wuauserv'
        Remove-Item 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate' -Recurse -Force
        Remove-Item ([IO.Path]::Combine($env:SystemRoot, 'SoftwareDistribution', '*')) -Recurse -Force

        & dism.exe /Online /Cleanup-Image /Restorehealth | Out-Null
        & sfc.exe /scannow | Out-Null

        Get-Service -Name 'wuauserv' | Set-Service -StartupType 'Automatic' | Out-Null
        Start-Service -Name 'wuauserv'
    }

    $altWindowsUpdate = {
        if (Get-Command -Name 'UsoClient.exe' -ErrorAction 'Ignore') {
            # wuauclt has been replaced by usoclient; if it exists, use it.
            & UsoClient.exe RefreshSettings StartScan StartDownload StartInstall
        } else {
            & wuauclt.exe /detectnow /updatenow
        }
    }

    if (-not $NoPSWindowsUpdate.IsPresent) {
        try {
            $installWindowsUpdate = @{
                MicrosoftUpdate = $true
                SendHistory = $true
                AcceptAll = $true
            }

            if ($ScheduleJob) {
                $installWindowsUpdate.Add('ScheduleJob', $ScheduleJob)
            }

            if ($ScheduleReboot) {
                $installWindowsUpdate.Add('ScheduleReboot', $ScheduleReboot)
            } else {
                $installWindowsUpdate.Add('AutoReboot', $true)
            }

            Install-WindowsUpdate @installWindowsUpdate -Verbose
        } catch {
            & $altWindowsUpdate
        }
    } else {
        & $altWindowsUpdate
    }
}
<#
.SYNOPSIS
Runs the given command in ComSpec (aka: Command Prompt).
.DESCRIPTION
This just runs a command in ComSpec by passing it to `Invoke-Run`. If you don't *need* ComSpec to run the command, it's normally best to just use `Invoke-Run`.
 
Returns the same object as `Invoke-Run`
 
```
@{
    'Process' = $proc; # The result from Start-Process; as returned from `Invoke-Run`.
    'StdOut' = $stdout;
    'StdErr' = $stderr;
}
```
.PARAMETER Cmd
Under normal usage, the string passed in here just gets appended to `cmd.exe /c `.
.PARAMETER KeepOpen
Applies /K instead of /C, but *why would you want to do this?*
 
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
.PARAMETER StringMod
Applies /S: Modifies the treatment of string after /C or /K (run cmd.exe below)
.PARAMETER Quiet
Applies /Q: Turns echo off
.PARAMETER DisableAutoRun
Applies /D: Disable execution of AutoRun commands from registry (see below)
.PARAMETER ANSI
Applies /A: Causes the output of internal commands to a pipe or file to be ANSI
.PARAMETER Unicode
Applies /U: Causes the output of internal commands to a pipe or file to be Unicode
.OUTPUTS
[Hashtable] As returned from `Invoke-Run`.
.EXAMPLE
Invoke-Cmd "MKLINK /D Temp C:\Temp"
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#invoke-cmd
#>

function Invoke-Cmd {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, Position=1)]
        [string]
        $Cmd,

        [Parameter(Mandatory=$false)]
        [switch]
        $KeepOpen,

        [Parameter(Mandatory=$false)]
        [switch]
        $StringMod,

        [Parameter(Mandatory=$false)]
        [switch]
        $Quiet,

        [Parameter(Mandatory=$false)]
        [switch]
        $DisableAutoRun,

        [Parameter(Mandatory=$false)]
        [switch]
        $ANSI,

        [Parameter(Mandatory=$false)]
        [switch]
        $Unicode
    )

    Write-Information "[Invoke-Cmd] > $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
    Write-Debug "[Invoke-Cmd] Function Invocation: $($MyInvocation | Out-String)"

    [System.Collections.ArrayList] $ArgumentList = @()
    if ($KeepOpen) {
        $ArgumentList.Add('/K')
    } else {
        $ArgumentList.Add('/C')
    }
    if ($StringMod)      { $ArgumentList.Add('/S') }
    if ($Quiet)          { $ArgumentList.Add('/Q') }
    if ($DisableAutoRun) { $ArgumentList.Add('/D') }
    if ($ANSI)           { $ArgumentList.Add('/A') }
    if ($Unicode)        { $ArgumentList.Add('/U') }
    $ArgumentList.Add($Cmd)

    Write-Verbose "[Invoke-Cmd] Executing: cmd $($ArgumentList -join ' ')"

    Write-Verbose "[Invoke-Cmd] Invoke-Run ..."
    $proc = Invoke-Run -FilePath $env:ComSpec -ArgumentList $ArgumentList
    Write-Verbose "[Invoke-Cmd] ExitCode: $($proc.Process.ExitCode)"

    Write-Information "[Invoke-Cmd] Return: $($proc | Out-String)"
    return $proc
}
<#
.SYNOPSIS
Download a file and validate the checksum.
.DESCRIPTION
Download a file; use a few methods based on performance preference testing:
 
- `Start-BitsTransfer`
- `Net.WebClient`
- `Invoke-WebRequest`
 
If the first one fails, the next one will be tried. Target directory will be automatically created.
A checksum will be validated if it is supplied.
.PARAMETER Uri
Uri to the File to be downloaded.
.PARAMETER OutFile
The full path of the file to be downloaded.
.PARAMETER OutFolder
Folder where you want the file to go. If this is specified, the file name is derived from the last segment of the Uri parameter.
.PARAMETER Checksum
A string containing the Algorithm and the Hash separated by a colon.
For example: "SHA256:AA24A85644ECCCAD7098327899A3C827A6BE2AE1474C7958C1500DCD55EE66D8"
 
The algorithm should be a valid algorithm recognized by `Get-FileHash`.
.EXAMPLE
Invoke-Download 'https://download3.vmware.com/software/CART23FQ4_WIN_2212/VMware-Horizon-Client-2212-8.8.0-21079405.exe' -OutFile (Join-Path $env:Temp 'VMware-Horizon-Client-2212-8.8.0-21079405.exe')
.EXAMPLE
Invoke-Download 'https://download3.vmware.com/software/CART23FQ4_WIN_2212/VMware-Horizon-Client-2212-8.8.0-21079405.exe' -OutFolder $env:Temp
.EXAMPLE
Invoke-Download 'https://download3.vmware.com/software/CART23FQ4_WIN_2212/VMware-Horizon-Client-2212-8.8.0-21079405.exe' -OutFolder $env:Temp -Checksum 'sha256:a0bac35619328f5f9aa56508572f343f7a388286768b31ab95377c37b052e5ac'
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#invoke-download
#>

function Invoke-Download {
    [CmdletBinding(DefaultParameterSetName = 'OutFile')]
    param (
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'OutFile')]
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'OutFolder')]
        [ValidateNotNullOrEmpty()]
        [uri]
        $Uri,

        [Parameter(Mandatory = $true, ParameterSetName = 'OutFile')]
        [ValidateNotNullOrEmpty()]
        [IO.FileInfo]
        $OutFile,

        [Parameter(Mandatory = $true, ParameterSetName = 'OutFolder')]
        [ValidateNotNullOrEmpty()]
        [IO.DirectoryInfo]
        $OutFolder,

        [Parameter(Mandatory = $false, ParameterSetName = 'OutFile', HelpMessage = 'A string containing the Algorithm and the Hash separated by a colon.')]
        [Parameter(Mandatory = $false, ParameterSetName = 'OutFolder', HelpMessage = 'A string containing the Algorithm and the Hash separated by a colon.')]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({
            if ($_.Split(':', 2)[0] -in (Get-Command 'Microsoft.PowerShell.Utility\Get-FileHash').Parameters.Algorithm.Attributes.ValidValues) {
                Write-Output $true
            } else {
                Throw ('The first part ("{1}") of argument "{0}" does not belong to the set specified by Get-FileHash''s Algorithm parameter. Supply a first part "{1}" that is in the set "{2}" and then try the command again.' -f @(
                    $_
                    $_.Split(':', 2)[0]
                    ((Get-Command 'Microsoft.PowerShell.Utility\Get-FileHash').Parameters.Algorithm.Attributes.ValidValues -join ', ')
                ))
            }
        })]
        [string]
        $Checksum
    )

    Write-Information ('[Invoke-Download] > {0}' -f ($MyInvocation.BoundParameters | ConvertTo-Json -Compress))
    Write-Debug ('[Invoke-Download] Function Invocation: {0}' -f ($MyInvocation | Out-String))

    if ($PSCmdlet.ParameterSetName -eq 'OutFolder') {
        [IO.FileInfo] $OutFile = [IO.Path]::Combine($OutFolder.FullName, $Uri.Segments[-1])
    }

    if (-not $OutFile.Directory.Exists) {
        New-Item -ItemType 'Directory' -Path $OutFile.Directory.FullName | Out-Null
        Write-Verbose ('[Invoke-Download] Directory created: {0}' -f $OutFile.Directory.FullName)
    }

    $startBitsTransfer = @{
        Source      = $Uri.AbsoluteUri
        Destination = $OutFile.FullName
        ErrorAction = 'Stop'
    }
    Write-Verbose ('[Invoke-Download] startBitsTransfer: {0}' -f ($startBitsTransfer | ConvertTo-Json))

    try {
        Start-BitsTransfer @startBitsTransfer
    } catch {
        Write-Warning ('[Invoke-Download] BitsTransfer Failed: {0}' -f $_)
        try {
            (New-Object Net.WebClient).DownloadFile($startBitsTransfer.Source, $startBitsTransfer.Destination)
        } catch {
            Write-Warning ('[Invoke-Download] WebClient Failed: {0}' -f $_)
            Invoke-WebRequest -Uri $startBitsTransfer.Source -OutFile $startBitsTransfer.Destination
        }
    }

    if ($Checksum) {
        $checksumAlgorithm, $checksumHash = $Checksum.Split(':', 2)

        $hash = Get-FileHash -LiteralPath $startBitsTransfer.Destination -Algorithm $checksumAlgorithm
        Write-Verbose ('[Invoke-Download] Downloaded File Hash: {0}' -f ($hash | ConvertTo-Json))

        if ($checksumHash -ne $hash.Hash) {
            Remove-Item -LiteralPath $startBitsTransfer.Destination -Force
            Throw ('Unexpected Hash; Downloaded file deleted!')
        }
    }

    $OutFile.Refresh()
    return $OutFile
}
<#
.SYNOPSIS
Get SeTakeOwnership, SeBackup and SeRestore privileges before executes next lines, script needs Admin privilege
.NOTES
Ref: https://stackoverflow.com/a/35843420/17552750
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#invoke-elevatecurrentprocess
#>

function Invoke-ElevateCurrentProcess {
    [CmdletBinding()]
    [OutputType([void])]
    param()

    Write-Information ('[Invoke-ElevateCurrentProcess] > {0}' -f ($MyInvocation.BoundParameters | ConvertTo-Json -Compress))
    Write-Debug ('[Invoke-ElevateCurrentProcess] Function Invocation: {0}' -f ($MyInvocation | Out-String))

    $import = '[DllImport("ntdll.dll")] public static extern int RtlAdjustPrivilege(ulong a, bool b, bool c, ref bool d);'
    $ntdll = Add-Type -Member $import -Name 'NtDll' -PassThru
    $privileges = @{
        SeTakeOwnership = 9
        SeBackup =  17
        SeRestore = 18
    }

    foreach ($privilege in $privileges.GetEnumerator()) {
        Write-Debug ('[Invoke-ElevateCurrentProcess] Adjusting Priv: {0}: {1}' -f $privilege.Name, $privilege.Value)
        $rtlAdjustPrivilege = $ntdll::RtlAdjustPrivilege($privilege.Value, 1, 0, [ref] 0)
        $returnedMessage = Get-TranslatedErrorCode $rtlAdjustPrivilege
        Write-Debug ('[Invoke-ElevateCurrentProcess] Adjusted Prif: {0}' -f ($returnedMessage | Select-Object '*' | Out-String))
    }
}
<#
.EXAMPLE
$MountPath.FullName | Invoke-ForceEmptyDirectory
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#invoke-forceemptydirectory
#>

function Invoke-ForceEmptyDirectory {
    [CmdletBinding()]
    [OutputType([void])]
    param (
        [Parameter(
            Mandatory=$true,
            Position=0,
            ParameterSetName="ParameterSetName",
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true,
            HelpMessage="Path to one or more locations."
        )]
        [Alias("PSPath")]
        [ValidateNotNullOrEmpty()]
        [IO.DirectoryInfo]
        $Path
    )

    begin {}

    process {
        foreach ($p in $Path) {
            if (-not $p.Exists) {
                New-Item -ItemType 'Directory' -Path $p.FullName -Force | Out-Null
                $p.Refresh()
            } else { # Path Exists
                if ((Get-ChildItem $p.FullName | Measure-Object).Count) {
                    # Path (Directory) is NOT empty.
                    try {
                        $p.FullName | Remove-Item -Recurse -Force
                    } catch [System.ComponentModel.Win32Exception] {
                        if ($_.Exception.Message -eq 'Access to the cloud file is denied') {
                            Write-Warning ('[{0}] {1}' -f $_.Exception.GetType().FullName, $_.Exception.Message)
                            # It seems the problem comes from a directory, not the files themselves,
                            # so using a small workaround using Get-ChildItem to list and then delete
                            # all files helps to get rid of all files.
                            foreach ($item in (Get-ChildItem -LiteralPath $p.FullName -File -Recurse)) {
                                Remove-Item -LiteralPath $item.Fullname -Recurse -Force
                            }
                        } else {
                            Throw $_
                        }
                    }
                    New-Item -ItemType 'Directory' -Path $p.FullName -Force | Out-Null
                    $p.Refresh()
                }
            }
        }
    }

    end {}
}
<#
.SYNOPSIS
Executes msiexec.exe to perform the following actions for MSI & MSP files and MSI product codes: install, uninstall, patch, repair, active setup.
.DESCRIPTION
Executes msiexec.exe to perform the following actions for MSI & MSP files and MSI product codes: install, uninstall, patch, repair, active setup.
If the -Action parameter is set to "Install" and the MSI is already installed, the function will exit.
Sets default switches to be passed to msiexec based on the preferences in the XML configuration file.
Automatically generates a log file name and creates a verbose log file for all msiexec operations.
Expects the MSI or MSP file to be located in the "Files" sub directory of the App Deploy Toolkit. Expects transform files to be in the same directory as the MSI file.
.PARAMETER Action
The action to perform. Options: Install, Uninstall, Patch, Repair, ActiveSetup.
.PARAMETER Path
The path to the MSI/MSP file or the product code of the installed MSI.
.PARAMETER Transforms
The name of the transform file(s) to be applied to the MSI. Relational paths from the working dir, then the MSI are looked for ... in that order.
Multiple transforms can be specified; separated by a comma.
.PARAMETER Patches
The name of the patch (msp) file(s) to be applied to the MSI for use with the "Install" action. The patch file is expected to be in the same directory as the MSI file.
.PARAMETER MsiDisplay
Overrides the default MSI Display Settings.
.PARAMETER Parameters
Overrides the default parameters specified in the XML configuration file. Install default is: "REBOOT=ReallySuppress /QB!". Uninstall default is: "REBOOT=ReallySuppress /QN".
.PARAMETER SecureParameters
Hides all parameters passed to the MSI or MSP file from the toolkit Log file.
.PARAMETER LoggingOptions
Overrides the default logging options specified in the XML configuration file. Default options are: "/log" (aka: "/L*v")
.PARAMETER WorkingDirectory
Overrides the working directory. The working directory is set to the location of the MSI file.
.PARAMETER SkipMSIAlreadyInstalledCheck
Skips the check to determine if the MSI is already installed on the system. Default is: $false.
.PARAMETER PassThru
Returns ExitCode, StdOut, and StdErr output from the process.
.PARAMETER LogFileF
When using [Redstone], this will be overridden via $PSDefaultParameters.
.EXAMPLE
# Installs an MSI
Invoke-MSI 'Adobe_FlashPlayer_11.2.202.233_x64_EN.msi'
.EXAMPLE
# Installs an MSI, applying a transform and overriding the default MSI toolkit parameters
Invoke-MSI -Action 'Install' -Path 'Adobe_FlashPlayer_11.2.202.233_x64_EN.msi' -Transform 'Adobe_FlashPlayer_11.2.202.233_x64_EN_01.mst' -Parameters '/QN'
.EXAMPLE
# Installs an MSI and stores the result of the execution into a variable by using the -PassThru option
[psobject] $ExecuteMSIResult = Invoke-MSI -Action 'Install' -Path 'Adobe_FlashPlayer_11.2.202.233_x64_EN.msi' -PassThru
.EXAMPLE
# Uninstalls an MSI using a product code
Invoke-MSI -Action 'Uninstall' -Path '{26923b43-4d38-484f-9b9e-de460746276c}'
.EXAMPLE
# Installs an MSP
Invoke-MSI -Action 'Patch' -Path 'Adobe_Reader_11.0.3_EN.msp'
.EXAMPLE
$msi = @{
    Action = 'Install'
    Parameters = @(
        'USERNAME="{0}"' -f $settings.Installer.UserName
        'COMPANYNAME="{0}"' -f $settings.Installer.CompanyName
        'SERIALNUMBER="{0}"' -f $settings.Installer.SerialNumber
    )
}
 
if ([Environment]::Is64BitOperatingSystem) {
    Invoke-MSI @msi -Path 'Origin2016Sr2Setup32and64Bit.msi'
} else {
    Invoke-MSI @msi -Path 'Origin2016Sr2Setup32Bit.msi'
}
.NOTES
Copyright (C) 2015 - PowerShell App Deployment Toolkit Team
Copyright (C) 2023 - Raymond Piller (VertigoRay)
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#invoke-msi
#>

function Invoke-MSI {
    [CmdletBinding()]
    [OutputType([hashtable])]
    Param (
        [Parameter(Mandatory = $false)]
        [ValidateSet('Install','Uninstall','Patch','Repair','ActiveSetup')]
        [string]
        $Action = 'Install',

        [Parameter(Position=0, Mandatory = $true, HelpMessage = 'Please enter either the path to the MSI/MSP file or the ProductCode')]
        [ValidateNotNullorEmpty()]
        [Alias('FilePath')]
        [string]
        $Path,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [string[]]
        $Transforms,

        [Parameter(Mandatory = $false)]
        [Alias('Arguments')]
        [ValidateNotNullorEmpty()]
        [string[]]
        $Parameters = @('REBOOT=ReallySuppress'),

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [switch]
        $SecureParameters = $false,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [string[]]
        $Patches,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [string]
        $LoggingOptions = '/log',

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [string]
        $WorkingDirectory = $PWD.Path,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [switch]
        $SkipMSIAlreadyInstalledCheck = $false,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [string]
        $MsiDisplay = '/qn',

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [string]
        $WindowStyle = 'Hidden',

        [Parameter(Mandatory = $false)]
        [ValidateNotNullorEmpty()]
        [bool]
        $PassThru = $true,

        [Parameter(Mandatory = $false, HelpMessage = 'When using [Redstone], this will be overridden via $PSDefaultParameters.')]
        [ValidateNotNullorEmpty()]
        [string]
        $LogFileF = "${env:Temp}\Invoke-Msi.{1}.{0}.log"
    )

    Write-Verbose "[Invoke-Msi] > $($MyInvocation.BoundParameters | ConvertTo-Json -Compress)"
    Write-Debug "[Invoke-Msi] Function Invocation: $($MyInvocation | Out-String)"


    ## Initialize variable indicating whether $Path variable is a Product Code or not
    $PathIsProductCode = ($Path -as [guid]) -as [bool]

    ## Build the MSI Parameters
    switch ($Action) {
        'Install' {
            $option = '/i'
            $msiDefaultParams = $MsiDisplay
        }
        'Uninstall' {
            $option = '/x'
            $msiDefaultParams = $MsiDisplay
        }
        'Patch' {
            $option = '/update'
            $msiDefaultParams = $MsiDisplay
        }
        'Repair' {
            $option = '/f'
            $msiDefaultParams = $MsiDisplay
        }
        'ActiveSetup' {
            $option = '/fups'
        }
    }

    ## If the MSI is in the Files directory, set the full path to the MSI
    if ($PathIsProductCode) {
        [string] $msiFile = $Path
        [string] $msiLogFile = $LogFileF -f "msi.${Action}", ($Path -as [guid]).Guid
    } else {
        [string] $msiFile = (Resolve-Path $Path -ErrorAction 'Stop').Path
        [string] $msiLogFile = $LogFileF -f "msi.${Action}", ($Path -as [IO.FileInfo]).BaseName
    }

    ## Set the working directory of the MSI
    if ((-not $PathIsProductCode) -and (-not $workingDirectory)) {
        [string] $workingDirectory = Split-Path -Path $msiFile -Parent
    }

    ## Enumerate all transforms specified, qualify the full path if possible and enclose in quotes
    [System.Collections.ArrayList] $mst = @()
    foreach ($transform in $Transforms) {
        try {
            $mst = Resolve-Path $transform -ErrorAction 'Stop'
        } catch [System.Management.Automation.ItemNotFoundException] {
            if ($workingDirectory) {
                $mst.Add((Join-Path "${workingDirectory}\${transform}" -Resolve -ErrorAction 'Stop')) | Out-Null
            } else {
                $mst.Add($transform) | Out-Null
            }
        }
    }
    [string] $mstFile = "`"$($mst -join ';')`""

    ## Enumerate all patches specified, qualify the full path if possible and enclose in quotes
    [System.Collections.ArrayList] $msp = @()
    foreach ($patch in $Patches) {
        try {
            $msp = Resolve-Path $patch -ErrorAction 'Stop'
        } catch [System.Management.Automation.ItemNotFoundException] {
            if ($workingDirectory) {
                $msp.Add((Join-Path "${workingDirectory}\${patch}" -Resolve -ErrorAction 'Stop')) | Out-Null
            } else {
                $msp.Add($patch) | Out-Null
            }
        }
    }
    [string] $mspFile = "`"$($msp -join ';')`""

    ## Get the ProductCode of the MSI
    if ($PathIsProductCode) {
        [string] $MSIProductCode = $Path
    } elseif ([IO.Path]::GetExtension($msiFile) -eq '.msi') {
        try {
            [hashtable] $Get_MsiTablePropertySplat = @{
                Path              = $msiFile;
                Table             = 'Property';
                ContinueOnError   = $false;
            }
            if ($mst) {
                $Get_MsiTablePropertySplat.Add('TransformPath', $mst)
            }

            [string] $MSIProductCode = Get-MsiTableProperty @Get_MsiTablePropertySplat | Select-Object -ExpandProperty 'ProductCode' -ErrorAction 'Stop'
            Write-Information "[Invoke-Msi] Got the ProductCode from the MSI file: ${MSIProductCode}"
        } catch {
            Write-Information "[Invoke-Msi] Failed to get the ProductCode from the MSI file. Continuing with requested action [${Action}].$([Environment]::NewLine)$([Environment]::NewLine)$_"
        }
    }

    ## Start building the MsiExec command line starting with the base action and file
    [System.Collections.ArrayList] $argsMSI = @()
    if ($msiDefaultParams) {
        $argsMSI.Add($msiDefaultParams) | Out-Null
    }
    $argsMSI.Add($option) | Out-Null
    ## Enclose the MSI file in quotes to avoid issues with spaces when running msiexec
    $argsMSI.Add("`"${msiFile}`"") | Out-Null
    if ($Transforms) {
        $argsMSI.Add("TRANSFORMS=${mstFile}") | Out-Null
        $argsMSI.Add("TRANSFORMSSECURE=1") | Out-Null
    }
    if ($Patches) {
        $argsMSI.Add("PATCH=${mspFile}") | Out-Null
    }
    if ($Parameters) {
        foreach ($param in $Parameters) {
            $argsMSI.Add($param) | Out-Null
        }
    }
    $argsMSI.Add($LoggingOptions) | Out-Null
    $argsMSI.Add("`"$msiLogFile`"") | Out-Null

    ## Check if the MSI is already installed. If no valid ProductCode to check, then continue with requested MSI action.
    [boolean] $IsMsiInstalled = $false
    if ($MSIProductCode -and (-not $SkipMSIAlreadyInstalledCheck)) {
        [psobject] $MsiInstalled = Get-InstalledApplication -ProductCode $MSIProductCode
        if ($MsiInstalled) {
            [boolean] $IsMsiInstalled = $true
        }
    } else {
        if ($Action -ine 'Install') {
            [boolean] $IsMsiInstalled = $true
        }
    }

    if ($IsMsiInstalled -and ($Action -ieq 'Install')) {
        Write-Information "[Invoke-Msi] The MSI is already installed on this system. Skipping action [${Action}]..."
    } elseif ($IsMsiInstalled -or ((-not $IsMsiInstalled) -and ($Action -eq 'Install'))) {
        Write-Information "[Invoke-Msi] Executing MSI action [${Action}]..."

        # Build the hashtable with the options that will be passed to Invoke-Run using splatting
        [hashtable] $invokeRun =  @{
            FilePath = (Get-Command 'msiexec' -ErrorAction 'Stop').Source
            ArgumentList = $argsMSI
            WindowStyle = $WindowStyle
            PassThru = $PassThru
            Wait = $true
        }
        if ($WorkingDirectory) {
            $invokeRun.Add( 'WorkingDirectory', $WorkingDirectory)
        }


        ## If MSI install, check to see if the MSI installer service is available or if another MSI install is already underway.
        ## Please note that a race condition is possible after this check where another process waiting for the MSI installer
        ## to become available grabs the MSI Installer mutex before we do. Not too concerned about this possible race condition.
        [boolean] $msiExecAvailable = Assert-IsMutexAvailable -MutexName 'Global\_MSIExecute'
        Start-Sleep -Seconds 1
        if (-not $msiExecAvailable) {
            # Default MSI exit code for install already in progress
            Write-Warning '[Invoke-Msi] Please complete in progress MSI installation before proceeding with this install.'
            $msg = Get-MsiExitCodeMessage 1618
            Write-Error "[Invoke-Msi] 1618: ${msg}"
            & $Redstone.Quit 1618 $false
        }


        # Call the Invoke-Run function
        if ($PassThru) {
            $result = Invoke-Run @invokeRun
            if ($result.Process.ExitCode -ne 0) {
                $msg = Get-MsiExitCodeMessage $result.Process.ExitCode -MsiLog $msiLogFile
                Write-Warning "[Invoke-Msi] $($result.Process.ExitCode): ${msg}"
            }
            Write-Information "[Invoke-Msi] Return: $($result | Out-String)"
            return $result
        } else {
            Invoke-Run @invokeRun | Out-Null
        }
    } else {
        Write-Warning "[Invoke-Msi] The MSI is not installed on this system. Skipping action [${Action}]..."
    }
}
<#
.SYNOPSIS
Invoke method on any object.
.DESCRIPTION
Invoke method on any object with or without using named parameters.
.PARAMETER InputObject
Specifies an object which has methods that can be invoked.
.PARAMETER MethodName
Specifies the name of a method to invoke.
.PARAMETER ArgumentList
Argument to pass to the method being executed. Allows execution of method without specifying named parameters.
.PARAMETER Parameter
Argument to pass to the method being executed. Allows execution of method by using named parameters.
.EXAMPLE
$ShellApp = New-Object -ComObject 'Shell.Application'
$null = Invoke-ObjectMethod -InputObject $ShellApp -MethodName 'MinimizeAll'
 
Minimizes all windows.
.EXAMPLE
$ShellApp = New-Object -ComObject 'Shell.Application'
$null = Invoke-ObjectMethod -InputObject $ShellApp -MethodName 'Explore' -Parameter @{'vDir'='C:\Windows'}
 
Opens the C:\Windows folder in a Windows Explorer window.
.NOTES
This is an internal script function and should typically not be called directly.
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#invoke-objectmethod
#>

function Invoke-ObjectMethod {
    [CmdletBinding(DefaultParameterSetName='Positional')]
    Param (
        [Parameter(Mandatory=$true,Position=0)]
        [ValidateNotNull()]
        [object]$InputObject,
        [Parameter(Mandatory=$true,Position=1)]
        [ValidateNotNullorEmpty()]
        [string]$MethodName,
        [Parameter(Mandatory=$false,Position=2,ParameterSetName='Positional')]
        [object[]]$ArgumentList,
        [Parameter(Mandatory=$true,Position=2,ParameterSetName='Named')]
        [ValidateNotNull()]
        [hashtable]$Parameter
    )

    Begin { }
    Process {
        If ($PSCmdlet.ParameterSetName -eq 'Named') {
            ## Invoke method by using parameter names
            Write-Output -InputObject $InputObject.GetType().InvokeMember($MethodName, [Reflection.BindingFlags]::InvokeMethod, $null, $InputObject, ([object[]]($Parameter.Values)), $null, $null, ([string[]]($Parameter.Keys)))
        }
        Else {
            ## Invoke method without using parameter names
            Write-Output -InputObject $InputObject.GetType().InvokeMember($MethodName, [Reflection.BindingFlags]::InvokeMethod, $null, $InputObject, $ArgumentList, $null, $null, $null)
        }
    }
    End { }
}
<#
.SYNOPSIS
Run a scriptblock that contains Pester tests that can be used for MECM Application Detection.
.DESCRIPTION
 
```powershell
$ppv = 'VertigoRay Assert-IsElevated 1.2.3'
$sb = {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]
        $FunctionName
    )
 
    Describe $FunctionName {
        It 'Return Boolean' {
            {
                & $FunctionName | Should -BeOfType 'System.Boolean'
            } | Should -Not -Throw
        }
    }
}
$params = @{
    FunctionName = 'Assert-IsElevated'
}
Invoke-PesterDetect -PesterScriptBlock $sb -PesterScriptBlockParam $params -PublisherProductVersion $ppv
```
.PARAMETER PesterScriptBlock
Pass in a ScriptBlock that contains a fully functional Pester test.
Here's a simple example of creating the ScriptBlock:
 
```powershell
$sb = {
    Describe 'Assert-IsElevated' {
        It 'Return Boolean' {
            {
                Assert-IsElevated | Should -BeOfType 'System.Boolean'
            } | Should -Not -Throw
        }
    }
}
Invoke-PesterDetect -PesterScriptBlock $sb
```
.PARAMETER PesterScriptBlockParam
This allows you to pass parameters into your ScriptBlock.
Here's a simple example of creating the ScriptBlock with a parameter and passing a value into it.
This PowerShell code is functionally identical to the code in the `PesterScriptBlock` parameter.:
 
```powershell
$sb = {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]
        $FunctionName
    )
 
    Describe $FunctionName {
        It 'Return Boolean' {
            {
                & $FunctionName | Should -BeOfType 'System.Boolean'
            } | Should -Not -Throw
        }
    }
}
$params = @{
    FunctionName = 'Assert-IsElevated'
}
Invoke-PesterDetect -PesterScriptBlock $sb -PesterScriptBlockParam $params
```
.PARAMETER PublisherProductVersion
This a string containing the Publisher, Product, and Version separated by spaces.
 
```powershell
$PublisherProductVersion = "$($settings.Publisher) $($settings.Product) $($settings.Version)"
```
 
Really, you can provide whatever you want here, whatever you provide will be put on the end of a successful detection message.
For example, if you set this to "Peanut Brittle" because you think it's amusing, your successful detection message will be:
 
> Detection SUCCESSFUL: Peanut Brittle
.PARAMETER DevMode
This script allows additional output when you're in you development environment.
This is important to address because detections scripts have [very strict StdOut requirements](https://learn.microsoft.com/en-us/previous-versions/system-center/system-center-2012-R2/gg682159(v=technet.10)#to-use-a-custom-script-to-determine-the-presence-of-a-deployment-type).
 
```powershell
$devMode = if ($MyInvocation.MyCommand.Name -eq 'detect.ps1') { $true } else { $false }
```
 
This example assumes that in your development environment, you've named your detections script `detect.ps1`.
This is the InvocationName when we running the dev version of the script, like in Windows Sandbox.
When SCCM calls detection, the detection script is put in a file named as a guid.
    i.e. fae94777-2c0d-4dd0-94f0-407f7cd07858.ps1
.EXAMPLE
Invoke-PesterDetect -PesterScriptBlock $sb -PesterScriptBlockParam $params -PublisherProductVersion $ppv
 
This will run the PowerShell code block below returning ONLY the `Detection SUCCESSFUL` message if the detection was successful.
 
```text
Detection SUCCESSFUL: VertigoRay Assert-IsElevated 1.2.3
```
 
It will return nothing if the detection failed.
If you want to see where detection is failing, add the `DevMode` parameter.
 
**Note**: if your want to see what the variables are set to, take a look at the *Description*.
.EXAMPLE
Invoke-PesterDetect -PesterScriptBlock $sb -PesterScriptBlockParam $params -PublisherProductVersion $ppv -DevMode
 
This will the pass with verbose output.
 
```text
Pester v5.3.3
 
Starting discovery in 1 files.
Discovery found 1 tests in 25ms.
Running tests.
Describing Assert-IsElevated
  [+] Return Boolean 26ms (15ms|11ms)
Tests completed in 174ms
Tests Passed: 1, Failed: 0, Skipped: 0 NotRun: 0
Detection SUCCESSFUL: VertigoRay Assert-IsElevated 1.2.3
```
 
**Note**: if your want to see what the variables are set to, take a look at the *Description*.
.EXAMPLE
Invoke-PesterDetect -PesterScriptBlock $sb -PesterScriptBlockParam @{ FunctionName = 'This-DoesNotExist' } -PublisherProductVersion $ppv -DevMode
 
This will fail with verbose output.
This is useful in development, but you wouldn't want to send this to production.
The reason is described in the `DevMode` parameter section.
 
```text
Pester v5.4.0
 
Starting discovery in 1 files.
Discovery found 1 tests in 48ms.
Running tests.
Describing This-DoesNotExist
  [-] Return Boolean 250ms (241ms|9ms)
   Expected no exception to be thrown, but an exception "The term 'This-DoesNotExist' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." was thrown from line:12 char:19
       + & $FunctionName | Should -BeOfType 'System.Boolean'
       + ~~~~~~~~~~~~~.
   at } | Should -Not -Throw, :13
   at <ScriptBlock>, <No file>:11
Tests completed in 593ms
Tests Passed: 0, Failed: 1, Skipped: 0 NotRun: 0
WARNING: [DEV MODE] Detection FAILED: VertigoRay Assert-IsElevated 1.2.3
```
 
**Note**: if your want to see what the variables are set to, take a look at the *Description*.
#>

function Invoke-PesterDetect {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [scriptblock]
        $PesterScriptBlock,

        [Parameter()]
        [hashtable]
        $PesterScriptBlockParam = @{},

        [Parameter(HelpMessage = '"$($settings.Publisher) $($settings.Product) $($settings.Version)"')]
        [string]
        $PublisherProductVersion = ':)',

        [Parameter()]
        [switch]
        $DevMode
    )

    $PesterPreference = [PesterConfiguration] @{
        Output = @{
            Verbosity = if ($DevMode) { 'Detailed' } else { 'None' }
        }
    }
    $container = New-PesterContainer -ScriptBlock $PesterScriptBlock -Data $PesterScriptBlockParam
    $testResults = Invoke-Pester -Container $container -PassThru

    if ($DevMode) {
        Write-Debug ('[Invoke-PesterDetect][DEV MODE] testResults: {0}' -f ($testResults | Out-String))
    }

    if ($testResults.Result -eq 'Passed') {
        Write-Output ('Detection SUCCESSFUL: {0}' -f $PublisherProductVersion)
    } elseif ($DevMode) {
        Write-Warning ('[Invoke-PesterDetect][DEV MODE] Detection FAILED: {0}' -f $PublisherProductVersion)
    }
}
<#
.NOTES
Ref: https://stackoverflow.com/a/35843420/17552750
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#invoke-registrytakeownership
#>

function Invoke-RegistryTakeOwnership {
    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory = $false)]
        [string]
        $RootKey,

        [Parameter(Mandatory = $true)]
        [string]
        $Key,

        [Parameter(Mandatory = $false)]
        [System.Security.Principal.SecurityIdentifier]
        $Sid,

        [Parameter(Mandatory = $false)]
        [bool]
        $Recurse = $true
    )

    Write-Information ('[Invoke-RegistryTakeOwnership] > {0}' -f ($MyInvocation.BoundParameters | ConvertTo-Json -Compress))
    Write-Debug ('[Invoke-RegistryTakeOwnership] Function Invocation: {0}' -f ($MyInvocation | Out-String))

    if (-not $RootKey -and ($Key -match '^(Microsoft\.PowerShell\.Core\\Registry\:\:|Registry\:\:)([^\\]+)\\(.*)')) {
        $RootKey = $Matches[2]
        $Key = $Matches[3]
    }

    switch -regex ($RootKey) {
        'HKCU|HKEY_CURRENT_USER'    { $RootKey = 'CurrentUser' }
        'HKLM|HKEY_LOCAL_MACHINE'   { $RootKey = 'LocalMachine' }
        'HKCR|HKEY_CLASSES_ROOT'    { $RootKey = 'ClassesRoot' }
        'HKCC|HKEY_CURRENT_CONFIG'  { $RootKey = 'CurrentConfig' }
        'HKU|HKEY_USERS'            { $RootKey = 'Users' }
    }

    # Escalate current process's privilege
    Invoke-ElevateCurrentProcess

    if (-not $Sid) {
        # Get Current User SID
        [System.Security.Principal.SecurityIdentifier] $Sid = (& whoami /USER | Select-Object -Last 1).Split(' ')[-1]
        Write-Verbose "[Invoke-RegistryTakeOwnership] Current User SID: $Sid"
    }
    Set-RegistryKeyPermissions $RootKey $Key $Sid $recurse
}
<#
.SYNOPSIS
Runs the given command.
.DESCRIPTION
This command sends a single command to `Start-Process` in a way that is standardized. For convenience, you can use the `Cmd` parameter, passing a single string that contains your executable and parameters; see examples.
 
The command will return a `[hashtable]` including the Process results, standard output, and standard error:
 
```
@{
    'Process' = $proc; # The result from Start-Process.
    'StdOut' = $stdout; # This is an array, as returned from `Get-Content`.
    'StdErr' = $stderr; # This is an array, as returned from `Get-Content`.
}
```
 
This function has been vetted for several years, but if you run into issues, try using `Start-Process`.
.PARAMETER Cmd
This is the command you wish to run, including arguments, as a single string.
.PARAMETER FilePath
Specifies the optional path and file name of the program that runs in the process. Enter the name of an executable file or of a document, such as a .txt or .doc file, that is associated with a program on the computer.
 
Passes Directly to `Start-Process`; see `Get-Help Start-Process`.
.PARAMETER ArgumentList
Specifies parameters or parameter values to use when this cmdlet starts the process.
 
Passes Directly to `Start-Process`; see `Get-Help Start-Process`.
.PARAMETER WorkingDirectory
Specifies the location of the executable file or document that runs in the process. The default is the current folder.
 
Passes Directly to `Start-Process`; see `Get-Help Start-Process`.
.PARAMETER PassThru
Returns a process object for each process that the cmdlet started. By default, this cmdlet does generate output.
 
Passes Directly to `Start-Process`; see `Get-Help Start-Process`.
.PARAMETER Wait
Indicates that this cmdlet waits for the specified process to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the process finishes.
 
Passes Directly to `Start-Process`; see `Get-Help Start-Process`.
.PARAMETER WindowStyle
Specifies the state of the window that is used for the new process. The acceptable values for this parameter are: Normal, Hidden, Minimized, and Maximized.
 
Passes Directly to `Start-Process`; see `Get-Help Start-Process`.
.OUTPUTS
[hashtable]
.EXAMPLE
$result = Invoke-Run """${firefox_setup_exe}"" /INI=""${ini}"""
Use `Cmd` parameter
.EXAMPLE
$result = Invoke-Run -FilePath $firefox_setup_exe -ArgumentList @("/INI=""${ini}""")
Use `FilePath` and `ArgumentList` parameters
.EXAMPLE
$result.Process.ExitCode
Get the ExitCode
.LINK
https://github.com/VertigoRay/PSRedstone/wiki/Functions#invoke-run
#>

function Invoke-Run {
    [CmdletBinding()]
    [OutputType([hashtable])]
    param (
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'Cmd')]
        [string]
        $Cmd,

        [Parameter(Mandatory = $true, ParameterSetName = 'FilePath')]
        [string]
        $FilePath,

        [Parameter(Mandatory = $false, ParameterSetName = 'FilePath')]
        [string[]]
        $ArgumentList,

        [Parameter(Mandatory = $false)]
        [switch]
        $CaptureConsoleOut,

        [Parameter(Mandatory = $false)]
        [string]
        $WorkingDirectory,

        [Parameter(Mandatory = $false)]
        [boolean]
        $PassThru = $true,

        [Parameter(Mandatory = $false)]
        [boolean]
        $Wait = $true,

        [Parameter(Mandatory = $false)]
        [string]
        $WindowStyle = 'Hidden',

        [Parameter(Mandatory = $false)]
        [IO.FileInfo]
        $LogFile
    )

    Write-Information ('[Invoke-Run] > {0}' -f ($MyInvocation.BoundParameters | ConvertTo-Json -Compress)) -Tags 'Redstone','Invoke-Run'
    Write-Debug ('[Invoke-Run] Function Invocation: {0}' -f ($MyInvocation | Out-String))

    if ($PsCmdlet.ParameterSetName -ieq 'Cmd') {
        Write-Verbose ('[Invoke-Run] Executing: {0}' -f $cmd)
        if ($Cmd -match '^(?:"([^"]+)")$|^(?:"([^"]+)") (.+)$|^(?:([^\s]+))$|^(?:([^\s]+)) (.+)$') {
            # https://regex101.com/r/uU4vH1/1

            Write-Verbose "Cmd Match: $($Matches | Out-String)"

            if ($Matches[1]) {
                $FilePath = $Matches[1]
            } elseif ($Matches[2]) {
                $FilePath = $Matches[2]
                $ArgumentList = $Matches[3]
            } elseif ($Matches[4]) {
                $FilePath = $Matches[4]
            } elseif ($Matches[5]) {
                $FilePath = $Matches[5]
                $ArgumentList = $Matches[6]
            }
        } else {
            Throw [System.Management.Automation.ParameterBindingException] ('Cmd Match Error: {0}' -f $cmd)
        }
    }

    [hashtable] $startProcess = @{
        FilePath                  = $FilePath
        PassThru                  = $PassThru
        Wait                      = $Wait
        WindowStyle               = $WindowStyle
    }

    if ($ArgumentList) {
        $startProcess.Add('ArgumentList', $ArgumentList)
    }

    if ($WorkingDirectory) {
        $startProcess.Add('WorkingDirectory', $WorkingDirectory)
    }

    if ($CaptureConsoleOut.IsPresent) {
        [IO.FileInfo] $stdout = New-TemporaryFile
        [IO.FileInfo] $stderr = New-TemporaryFile

        while (-not $stdout.Exists -or -not $stderr.Exists) {
            # Sometimes this is too fast
            # Let's wait for the tmp file to show up.
            Start-Sleep -Milliseconds 100
            $stdout.Refresh()
            $stderr.Refresh()
        }

        $startProcess.Add('RedirectStandardOutput', $stdout.FullName)
        $startProcess.Add('RedirectStandardError', $stderr.FullName)

        $monScript = {
            Param ([string] $Std, [IO.FileInfo] $Tmp, [IO.FileInfo] $LogFile)
            Get-Content $Tmp.FullName -Wait | ForEach-Object {
                ('STD{0}: {1}' -f $Std.ToUpper(), $_) | Out-File -Encoding 'utf8' -LiteralPath $LogFile.FullName -Append -Force
            }
        }

        $stdoutMon = [powershell]::Create()
        [void] $stdoutMon.AddScript($monScript).AddParameters(@{
            Std = 'Out'
            Tmp = $stdout.FullName
            LogFile = $LogFile.