OhMyPsh.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
## Pre-Loaded Module code ##

param(
    [parameter(Position=0)]
    [string]$UserProfilePath
)

if (-not [string]::IsNullOrEmpty($UserProfilePath)) {
    if ((Test-Path -Path $UserProfilePath -PathType:Container)) {
        $Script:UserProfilePath = Resolve-Path -Path $UserProfilePath
    }
    else {
        throw "Invalid OhMyPsh profile path: $UserProfilePath"
    }
}
else {
        if ((Get-Variable 'PROFILE' -ErrorAction:SilentlyContinue) -eq $null) {
        throw 'No profile variable found!'
    }
    $Script:UserProfilePath = Split-Path $PROFILE
}

$OMPProfileExportFile = Join-Path $UserProfilePath '.OhMyPsh.config.json'
$IsConEmuConsole = if ($null -ne $env:ConEmuANSI) {$true} else {$false}

# Backup some basic host settings. these never get updated and are used for restore purposes.
$Script:HostState = @{
    Title = $Host.UI.RawUI.WindowTitle
    Background = $Host.UI.RawUI.BackgroundColor
    Foreground = $Host.UI.RawUI.ForegroundColor
    Prompt = $function:prompt
    TabExpansion = $function:TabExpansion
    TabExpansion2 = $function:TabExpansion2
    PSDefaultParameterValues =  $Global:PSDefaultParameterValues.Clone()
    Aliases = Join-Path $UserProfilePath '.OhMyPsh.aliasbackup.ps1'
    Modules = (Get-Module).Name
    Colors = @{
        BackgroundColor = $Host.UI.RawUI.BackgroundColor
        ForegroundColor = $Host.UI.RawUI.ForegroundColor
        ErrorForegroundColor = $Host.PrivateData.ErrorForegroundColor
        WarningForegroundColor = $Host.PrivateData.WarningForegroundColor
        DebugForegroundColor = $Host.PrivateData.DebugForegroundColor
        VerboseForegroundColor = $Host.PrivateData.VerboseForegroundColor
        ProgressForegroundColor = $Host.PrivateData.ProgressForegroundColor
        ErrorBackgroundColor = $Host.PrivateData.ErrorBackgroundColor
        WarningBackgroundColor  = $Host.PrivateData.WarningBackgroundColor
        DebugBackgroundColor = $Host.PrivateData.DebugBackgroundColor
        VerboseBackgroundColor = $Host.PrivateData.VerboseBackgroundColor
        ProgressBackgroundColor = $Host.PrivateData.ProgressBackgroundColor
    }
}

if (get-module psreadline) {
    $Script:PSReadlineState = Get-PSReadlineOption
}
else {
    $Script:PSReadlineState = $null
}

if (-not $Script:ModulePath) {
    $ModulePath = Split-Path $script:MyInvocation.MyCommand.Path
}

# Backup original aliases
Get-Alias | Where {($_.Options -split ',') -notcontains 'ReadOnly'} | Export-Alias -Path $Script:HostState['Aliases'] -As Script -Force

## PRIVATE MODULE FUNCTIONS AND DATA ##

function Get-CallerPreference {
    <#
    .Synopsis
       Fetches "Preference" variable values from the caller's scope.
    .DESCRIPTION
       Script module functions do not automatically inherit their caller's variables, but they can be
       obtained through the $PSCmdlet variable in Advanced Functions. This function is a helper function
       for any script module Advanced Function; by passing in the values of $ExecutionContext.SessionState
       and $PSCmdlet, Get-CallerPreference will set the caller's preference variables locally.
    .PARAMETER Cmdlet
       The $PSCmdlet object from a script module Advanced Function.
    .PARAMETER SessionState
       The $ExecutionContext.SessionState object from a script module Advanced Function. This is how the
       Get-CallerPreference function sets variables in its callers' scope, even if that caller is in a different
       script module.
    .PARAMETER Name
       Optional array of parameter names to retrieve from the caller's scope. Default is to retrieve all
       Preference variables as defined in the about_Preference_Variables help file (as of PowerShell 4.0)
       This parameter may also specify names of variables that are not in the about_Preference_Variables
       help file, and the function will retrieve and set those as well.
    .EXAMPLE
       Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
 
       Imports the default PowerShell preference variables from the caller into the local scope.
    .EXAMPLE
       Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState -Name 'ErrorActionPreference','SomeOtherVariable'
 
       Imports only the ErrorActionPreference and SomeOtherVariable variables into the local scope.
    .EXAMPLE
       'ErrorActionPreference','SomeOtherVariable' | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
 
       Same as Example 2, but sends variable names to the Name parameter via pipeline input.
    .INPUTS
       String
    .OUTPUTS
       None. This function does not produce pipeline output.
    .LINK
       about_Preference_Variables
    #>


    [CmdletBinding(DefaultParameterSetName = 'AllVariables')]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateScript({ $_.GetType().FullName -eq 'System.Management.Automation.PSScriptCmdlet' })]
        $Cmdlet,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.SessionState]$SessionState,

        [Parameter(ParameterSetName = 'Filtered', ValueFromPipeline = $true)]
        [string[]]$Name
    )

    begin {
        $filterHash = @{}
    }
    
    process {
        if ($null -ne $Name)
        {
            foreach ($string in $Name)
            {
                $filterHash[$string] = $true
            }
        }
    }

    end {
        # List of preference variables taken from the about_Preference_Variables help file in PowerShell version 4.0

        $vars = @{
            'ErrorView' = $null
            'FormatEnumerationLimit' = $null
            'LogCommandHealthEvent' = $null
            'LogCommandLifecycleEvent' = $null
            'LogEngineHealthEvent' = $null
            'LogEngineLifecycleEvent' = $null
            'LogProviderHealthEvent' = $null
            'LogProviderLifecycleEvent' = $null
            'MaximumAliasCount' = $null
            'MaximumDriveCount' = $null
            'MaximumErrorCount' = $null
            'MaximumFunctionCount' = $null
            'MaximumHistoryCount' = $null
            'MaximumVariableCount' = $null
            'OFS' = $null
            'OutputEncoding' = $null
            'ProgressPreference' = $null
            'PSDefaultParameterValues' = $null
            'PSEmailServer' = $null
            'PSModuleAutoLoadingPreference' = $null
            'PSSessionApplicationName' = $null
            'PSSessionConfigurationName' = $null
            'PSSessionOption' = $null

            'ErrorActionPreference' = 'ErrorAction'
            'DebugPreference' = 'Debug'
            'ConfirmPreference' = 'Confirm'
            'WhatIfPreference' = 'WhatIf'
            'VerbosePreference' = 'Verbose'
            'WarningPreference' = 'WarningAction'
        }

        foreach ($entry in $vars.GetEnumerator()) {
            if (([string]::IsNullOrEmpty($entry.Value) -or -not $Cmdlet.MyInvocation.BoundParameters.ContainsKey($entry.Value)) -and
                ($PSCmdlet.ParameterSetName -eq 'AllVariables' -or $filterHash.ContainsKey($entry.Name))) {
                
                $variable = $Cmdlet.SessionState.PSVariable.Get($entry.Key)
                
                if ($null -ne $variable) {
                    if ($SessionState -eq $ExecutionContext.SessionState) {
                        Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
                    }
                    else {
                        $SessionState.PSVariable.Set($variable.Name, $variable.Value)
                    }
                }
            }
        }

        if ($PSCmdlet.ParameterSetName -eq 'Filtered') {
            foreach ($varName in $filterHash.Keys) {
                if (-not $vars.ContainsKey($varName)) {
                    $variable = $Cmdlet.SessionState.PSVariable.Get($varName)
                
                    if ($null -ne $variable)
                    {
                        if ($SessionState -eq $ExecutionContext.SessionState)
                        {
                            Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
                        }
                        else
                        {
                            $SessionState.PSVariable.Set($variable.Name, $variable.Value)
                        }
                    }
                }
            }
        }
    }
}

Function Invoke-OMPPersonalFunction {
    <#
    .SYNOPSIS
        Dot sources a personal function file in the global context and tags it to ohmypsh.
    .DESCRIPTION
        Dot sources a personal function file in the global context and tags it to ohmypsh.
    .PARAMETER Path
        Path for the file to import.
    .PARAMETER Tag
        Tag to place on the function (in the form of a noteproperty).
    .EXAMPLE
        TBD
    .NOTES
        Author: Zachary Loeber
 
 
        Version History
        1.0.0 - Initial release
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
        [string]$Path,
        [Parameter(Position = 1, Mandatory = $true)]
        [string]$Tag
    )

    Begin {
        Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        Write-Verbose "Attempting to load the file $Path"
    }

    Process {
        if (Test-Path $Path) {
            $errmsg = $null

            # Load the script, replace any root level functions with its global equivalent. Then invoke.
            $script = (Get-Content $Path -Raw) -replace '^function\s+((?!global[:]|local[:]|script[:]|private[:])[\w-]+)', 'function Global:$1'
            try {
                $sb = [Scriptblock]::create(".{$script}")
                Invoke-Command -NoNewScope -ScriptBlock $sb -ErrorVariable errmsg 2>$null
                if (-not ([string]::IsNullOrEmpty($errmsg))) {
                    throw "Unable to load script file $Path"
                }
            }
            catch {
                throw "Unable to load script file $Path"
            }

            # Next look for any globally defined functions and tag them with a noteproperty to track
            ([System.Management.Automation.Language.Parser]::ParseInput($script, [ref]$null, [ref]$null)).FindAll({ $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $false) | Foreach-Object {
                if (($_.Name).StartsWith('Global:')) {
                    $globalfunc = Get-ChildItem -Path "Function:\$($_.Name -replace 'Global:','')" -ErrorAction:SilentlyContinue
                    if ($GlobalFunc -ne $null) {
                        Write-Verbose "Function exported into the global session: $($_.Name -replace 'Global:','')"
                        try {
                            $globalfunc | Add-Member -MemberType 'NoteProperty' -Name 'ohmypsh' -Value $Tag -Force
                        }
                        catch {
                            # Do nothing as the member probably already existed.
                        }
                    }
                }
            }
        }
        else {
            throw "Invalid Path: $Path"
        }
    }
}

function New-DynamicParameter {
    <#
    .SYNOPSIS
    Helper function to simplify creating dynamic parameters
 
    .DESCRIPTION
    Helper function to simplify creating dynamic parameters.
 
    Example use cases:
        Include parameters only if your environment dictates it
        Include parameters depending on the value of a user-specified parameter
        Provide tab completion and intellisense for parameters, depending on the environment
 
    Please keep in mind that all dynamic parameters you create, will not have corresponding variables created.
        Use New-DynamicParameter with 'CreateVariables' switch in your main code block,
        ('Process' for advanced functions) to create those variables.
        Alternatively, manually reference $PSBoundParameters for the dynamic parameter value.
 
    This function has two operating modes:
 
    1. All dynamic parameters created in one pass using pipeline input to the function. This mode allows to create dynamic parameters en masse,
    with one function call. There is no need to create and maintain custom RuntimeDefinedParameterDictionary.
 
    2. Dynamic parameters are created by separate function calls and added to the RuntimeDefinedParameterDictionary you created beforehand.
    Then you output this RuntimeDefinedParameterDictionary to the pipeline. This allows more fine-grained control of the dynamic parameters,
    with custom conditions and so on.
 
    .NOTES
    Credits to jrich523 and ramblingcookiemonster for their initial code and inspiration:
        https://github.com/RamblingCookieMonster/PowerShell/blob/master/New-DynamicParam.ps1
        http://ramblingcookiemonster.wordpress.com/2014/11/27/quick-hits-credentials-and-dynamic-parameters/
        http://jrich523.wordpress.com/2013/05/30/powershell-simple-way-to-add-dynamic-parameters-to-advanced-function/
 
    Credit to BM for alias and type parameters and their handling
 
    .PARAMETER Name
    Name of the dynamic parameter
 
    .PARAMETER Type
    Type for the dynamic parameter. Default is string
 
    .PARAMETER Alias
    If specified, one or more aliases to assign to the dynamic parameter
 
    .PARAMETER Mandatory
    If specified, set the Mandatory attribute for this dynamic parameter
 
    .PARAMETER Position
    If specified, set the Position attribute for this dynamic parameter
 
    .PARAMETER HelpMessage
    If specified, set the HelpMessage for this dynamic parameter
 
    .PARAMETER DontShow
    If specified, set the DontShow for this dynamic parameter.
    This is the new PowerShell 4.0 attribute that hides parameter from tab-completion.
    http://www.powershellmagazine.com/2013/07/29/pstip-hiding-parameters-from-tab-completion/
 
    .PARAMETER ValueFromPipeline
    If specified, set the ValueFromPipeline attribute for this dynamic parameter
 
    .PARAMETER ValueFromPipelineByPropertyName
    If specified, set the ValueFromPipelineByPropertyName attribute for this dynamic parameter
 
    .PARAMETER ValueFromRemainingArguments
    If specified, set the ValueFromRemainingArguments attribute for this dynamic parameter
 
    .PARAMETER ParameterSetName
    If specified, set the ParameterSet attribute for this dynamic parameter. By default parameter is added to all parameters sets.
 
    .PARAMETER AllowNull
    If specified, set the AllowNull attribute of this dynamic parameter
 
    .PARAMETER AllowEmptyString
    If specified, set the AllowEmptyString attribute of this dynamic parameter
 
    .PARAMETER AllowEmptyCollection
    If specified, set the AllowEmptyCollection attribute of this dynamic parameter
 
    .PARAMETER ValidateNotNull
    If specified, set the ValidateNotNull attribute of this dynamic parameter
 
    .PARAMETER ValidateNotNullOrEmpty
    If specified, set the ValidateNotNullOrEmpty attribute of this dynamic parameter
 
    .PARAMETER ValidateRange
    If specified, set the ValidateRange attribute of this dynamic parameter
 
    .PARAMETER ValidateLength
    If specified, set the ValidateLength attribute of this dynamic parameter
 
    .PARAMETER ValidatePattern
    If specified, set the ValidatePattern attribute of this dynamic parameter
 
    .PARAMETER ValidateScript
    If specified, set the ValidateScript attribute of this dynamic parameter
 
    .PARAMETER ValidateSet
    If specified, set the ValidateSet attribute of this dynamic parameter
 
    .PARAMETER ParameterDefaultValue
    If specified, set a default value for the parameter.
 
    .PARAMETER Dictionary
    If specified, add resulting RuntimeDefinedParameter to an existing RuntimeDefinedParameterDictionary.
    Appropriate for custom dynamic parameters creation.
 
    If not specified, create and return a RuntimeDefinedParameterDictionary
    Aappropriate for a simple dynamic parameter creation.
 
    .EXAMPLE
    Create one dynamic parameter.
 
    This example illustrates the use of New-DynamicParameter to create a single dynamic parameter.
    The Drive's parameter ValidateSet is populated with all available volumes on the computer for handy tab completion / intellisense.
 
    Usage: Get-FreeSpace -Drive <tab>
 
    function Get-FreeSpace
    {
        [CmdletBinding()]
        Param()
        DynamicParam
        {
            # Get drive names for ValidateSet attribute
            $DriveList = ([System.IO.DriveInfo]::GetDrives()).Name
 
            # Create new dynamic parameter
            New-DynamicParameter -Name Drive -ValidateSet $DriveList -Type ([array]) -Position 0 -Mandatory
        }
 
        Process
        {
            # Dynamic parameters don't have corresponding variables created,
            # you need to call New-DynamicParameter with CreateVariables switch to fix that.
            New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
 
            $DriveInfo = [System.IO.DriveInfo]::GetDrives() | Where-Object {$Drive -contains $_.Name}
            $DriveInfo |
                ForEach-Object {
                    if(!$_.TotalFreeSpace)
                    {
                        $FreePct = 0
                    }
                    else
                    {
                        $FreePct = [System.Math]::Round(($_.TotalSize / $_.TotalFreeSpace), 2)
                    }
                    New-Object -TypeName psobject -Property @{
                        Drive = $_.Name
                        DriveType = $_.DriveType
                        'Free(%)' = $FreePct
                    }
                }
        }
    }
 
    .EXAMPLE
    Create several dynamic parameters not using custom RuntimeDefinedParameterDictionary (requires piping).
 
    In this example two dynamic parameters are created. Each parameter belongs to the different parameter set, so they are mutually exclusive.
 
    The Drive's parameter ValidateSet is populated with all available volumes on the computer.
    The DriveType's parameter ValidateSet is populated with all available drive types.
 
    Usage: Get-FreeSpace -Drive <tab>
        or
    Usage: Get-FreeSpace -DriveType <tab>
 
    Parameters are defined in the array of hashtables, which is then piped through the New-Object to create PSObject and pass it to the New-DynamicParameter function.
    Because of piping, New-DynamicParameter function is able to create all parameters at once, thus eliminating need for you to create and pass external RuntimeDefinedParameterDictionary to it.
 
    function Get-FreeSpace
    {
        [CmdletBinding()]
        Param()
        DynamicParam
        {
            # Array of hashtables that hold values for dynamic parameters
            $DynamicParameters = @(
                @{
                    Name = 'Drive'
                    Type = [array]
                    Position = 0
                    Mandatory = $true
                    ValidateSet = ([System.IO.DriveInfo]::GetDrives()).Name
                    ParameterSetName = 'Drive'
                },
                @{
                    Name = 'DriveType'
                    Type = [array]
                    Position = 0
                    Mandatory = $true
                    ValidateSet = [System.Enum]::GetNames('System.IO.DriveType')
                    ParameterSetName = 'DriveType'
                }
            )
 
            # Convert hashtables to PSObjects and pipe them to the New-DynamicParameter,
            # to create all dynamic paramters in one function call.
            $DynamicParameters | ForEach-Object {New-Object PSObject -Property $_} | New-DynamicParameter
        }
        Process
        {
            # Dynamic parameters don't have corresponding variables created,
            # you need to call New-DynamicParameter with CreateVariables switch to fix that.
            New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
 
            if($Drive)
            {
                $Filter = {$Drive -contains $_.Name}
            }
            elseif($DriveType)
            {
                $Filter = {$DriveType -contains $_.DriveType}
            }
 
            $DriveInfo = [System.IO.DriveInfo]::GetDrives() | Where-Object $Filter
            $DriveInfo |
                ForEach-Object {
                    if(!$_.TotalFreeSpace)
                    {
                        $FreePct = 0
                    }
                    else
                    {
                        $FreePct = [System.Math]::Round(($_.TotalSize / $_.TotalFreeSpace), 2)
                    }
                    New-Object -TypeName psobject -Property @{
                        Drive = $_.Name
                        DriveType = $_.DriveType
                        'Free(%)' = $FreePct
                    }
                }
        }
    }
 
    .EXAMPLE
    Create several dynamic parameters, with multiple Parameter Sets, not using custom RuntimeDefinedParameterDictionary (requires piping).
 
    In this example three dynamic parameters are created. Two of the parameters are belong to the different parameter set, so they are mutually exclusive.
    One of the parameters belongs to both parameter sets.
 
    The Drive's parameter ValidateSet is populated with all available volumes on the computer.
    The DriveType's parameter ValidateSet is populated with all available drive types.
    The DriveType's parameter ValidateSet is populated with all available drive types.
    The Precision's parameter controls number of digits after decimal separator for Free Space percentage.
 
    Usage: Get-FreeSpace -Drive <tab> -Precision 2
        or
    Usage: Get-FreeSpace -DriveType <tab> -Precision 2
 
    Parameters are defined in the array of hashtables, which is then piped through the New-Object to create PSObject and pass it to the New-DynamicParameter function.
    If parameter with the same name already exist in the RuntimeDefinedParameterDictionary, a new Parameter Set is added to it.
    Because of piping, New-DynamicParameter function is able to create all parameters at once, thus eliminating need for you to create and pass external RuntimeDefinedParameterDictionary to it.
 
    function Get-FreeSpace
    {
        [CmdletBinding()]
        Param()
        DynamicParam
        {
            # Array of hashtables that hold values for dynamic parameters
            $DynamicParameters = @(
                @{
                    Name = 'Drive'
                    Type = [array]
                    Position = 0
                    Mandatory = $true
                    ValidateSet = ([System.IO.DriveInfo]::GetDrives()).Name
                    ParameterSetName = 'Drive'
                },
                @{
                    Name = 'DriveType'
                    Type = [array]
                    Position = 0
                    Mandatory = $true
                    ValidateSet = [System.Enum]::GetNames('System.IO.DriveType')
                    ParameterSetName = 'DriveType'
                },
                @{
                    Name = 'Precision'
                    Type = [int]
                    # This will add a Drive parameter set to the parameter
                    Position = 1
                    ParameterSetName = 'Drive'
                },
                @{
                    Name = 'Precision'
                    # Because the parameter already exits in the RuntimeDefinedParameterDictionary,
                    # this will add a DriveType parameter set to the parameter.
                    Position = 1
                    ParameterSetName = 'DriveType'
                }
            )
 
            # Convert hashtables to PSObjects and pipe them to the New-DynamicParameter,
            # to create all dynamic paramters in one function call.
            $DynamicParameters | ForEach-Object {New-Object PSObject -Property $_} | New-DynamicParameter
        }
        Process
        {
            # Dynamic parameters don't have corresponding variables created,
            # you need to call New-DynamicParameter with CreateVariables switch to fix that.
            New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
 
            if($Drive)
            {
                $Filter = {$Drive -contains $_.Name}
            }
            elseif($DriveType)
            {
                $Filter = {$DriveType -contains $_.DriveType}
            }
 
            if(!$Precision)
            {
                $Precision = 2
            }
 
            $DriveInfo = [System.IO.DriveInfo]::GetDrives() | Where-Object $Filter
            $DriveInfo |
                ForEach-Object {
                    if(!$_.TotalFreeSpace)
                    {
                        $FreePct = 0
                    }
                    else
                    {
                        $FreePct = [System.Math]::Round(($_.TotalSize / $_.TotalFreeSpace), $Precision)
                    }
                    New-Object -TypeName psobject -Property @{
                        Drive = $_.Name
                        DriveType = $_.DriveType
                        'Free(%)' = $FreePct
                    }
                }
        }
    }
 
    .Example
    Create dynamic parameters using custom dictionary.
 
    In case you need more control, use custom dictionary to precisely choose what dynamic parameters to create and when.
    The example below will create DriveType dynamic parameter only if today is not a Friday:
 
    function Get-FreeSpace
    {
        [CmdletBinding()]
        Param()
        DynamicParam
        {
            $Drive = @{
                Name = 'Drive'
                Type = [array]
                Position = 0
                Mandatory = $true
                ValidateSet = ([System.IO.DriveInfo]::GetDrives()).Name
                ParameterSetName = 'Drive'
            }
 
            $DriveType = @{
                Name = 'DriveType'
                Type = [array]
                Position = 0
                Mandatory = $true
                ValidateSet = [System.Enum]::GetNames('System.IO.DriveType')
                ParameterSetName = 'DriveType'
            }
 
            # Create dictionary
            $DynamicParameters = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
 
            # Add new dynamic parameter to dictionary
            New-DynamicParameter @Drive -Dictionary $DynamicParameters
 
            # Add another dynamic parameter to dictionary, only if today is not a Friday
            if((Get-Date).DayOfWeek -ne [DayOfWeek]::Friday)
            {
                New-DynamicParameter @DriveType -Dictionary $DynamicParameters
            }
 
            # Return dictionary with dynamic parameters
            $DynamicParameters
        }
        Process
        {
            # Dynamic parameters don't have corresponding variables created,
            # you need to call New-DynamicParameter with CreateVariables switch to fix that.
            New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
 
            if($Drive)
            {
                $Filter = {$Drive -contains $_.Name}
            }
            elseif($DriveType)
            {
                $Filter = {$DriveType -contains $_.DriveType}
            }
 
            $DriveInfo = [System.IO.DriveInfo]::GetDrives() | Where-Object $Filter
            $DriveInfo |
                ForEach-Object {
                    if(!$_.TotalFreeSpace)
                    {
                        $FreePct = 0
                    }
                    else
                    {
                        $FreePct = [System.Math]::Round(($_.TotalSize / $_.TotalFreeSpace), 2)
                    }
                    New-Object -TypeName psobject -Property @{
                        Drive = $_.Name
                        DriveType = $_.DriveType
                        'Free(%)' = $FreePct
                    }
                }
        }
    }
    #>

    [CmdletBinding(PositionalBinding = $false, DefaultParameterSetName = 'DynamicParameter')]
    Param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [System.Type]$Type = [int],

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [string[]]$Alias,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$Mandatory,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [int]$Position,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [string]$HelpMessage,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$DontShow,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$ValueFromPipeline,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$ValueFromPipelineByPropertyName,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$ValueFromRemainingArguments,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [string]$ParameterSetName = '__AllParameterSets',

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$AllowNull,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$AllowEmptyString,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$AllowEmptyCollection,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$ValidateNotNull,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [switch]$ValidateNotNullOrEmpty,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateCount(2, 2)]
        [int[]]$ValidateCount,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateCount(2, 2)]
        [int[]]$ValidateRange,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateCount(2, 2)]
        [int[]]$ValidateLength,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateNotNullOrEmpty()]
        [string]$ValidatePattern,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateNotNullOrEmpty()]
        [scriptblock]$ValidateScript,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateNotNullOrEmpty()]
        [string[]]$ValidateSet,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateNotNullOrEmpty()]
        $ParameterDefaultValue,

        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                if (!($_ -is [System.Management.Automation.RuntimeDefinedParameterDictionary])) {
                    Throw 'Dictionary must be a System.Management.Automation.RuntimeDefinedParameterDictionary object'
                }
                $true
            })]
        $Dictionary = $false,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'CreateVariables')]
        [switch]$CreateVariables,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'CreateVariables')]
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                # System.Management.Automation.PSBoundParametersDictionary is an internal sealed class,
                # so one can't use PowerShell's '-is' operator to validate type.
                if ($_.GetType().Name -ne 'PSBoundParametersDictionary') {
                    Throw 'BoundParameters must be a System.Management.Automation.PSBoundParametersDictionary object'
                }
                $true
            })]
        $BoundParameters
    )

    Begin {
        Write-Verbose 'Creating new dynamic parameters dictionary'
        $InternalDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary

        Write-Verbose 'Getting common parameters'
        function _temp { [CmdletBinding()] Param() }
        $CommonParameters = (Get-Command _temp).Parameters.Keys
    }

    Process {
        if ($CreateVariables) {
            Write-Verbose 'Creating variables from bound parameters'
            Write-Debug 'Picking out bound parameters that are not in common parameters set'
            $BoundKeys = $BoundParameters.Keys | Where-Object { $CommonParameters -notcontains $_ }

            foreach ($Parameter in $BoundKeys) {
                Write-Debug "Setting existing variable for dynamic parameter '$Parameter' with value '$($BoundParameters.$Parameter)'"
                Set-Variable -Name $Parameter -Value $BoundParameters.$Parameter -Scope 1 -Force
            }
        }
        else {
            Write-Verbose 'Looking for cached bound parameters'
            Write-Debug 'More info: https://beatcracker.wordpress.com/2014/12/18/psboundparameters-pipeline-and-the-valuefrompipelinebypropertyname-parameter-attribute'
            $StaleKeys = @()
            $StaleKeys = $PSBoundParameters.GetEnumerator() |
                ForEach-Object {
                if ($_.Value.PSobject.Methods.Name -match '^Equals$') {
                    # If object has Equals, compare bound key and variable using it
                    if (!$_.Value.Equals((Get-Variable -Name $_.Key -ValueOnly -Scope 0))) {
                        $_.Key
                    }
                }
                else {
                    # If object doesn't has Equals (e.g. $null), fallback to the PowerShell's -ne operator
                    if ($_.Value -ne (Get-Variable -Name $_.Key -ValueOnly -Scope 0)) {
                        $_.Key
                    }
                }
            }
            if ($StaleKeys) {
                [string[]]"Found $($StaleKeys.Count) cached bound parameters:" + $StaleKeys | Write-Debug
                Write-Verbose 'Removing cached bound parameters'
                $StaleKeys | ForEach-Object {[void]$PSBoundParameters.Remove($_)}
            }

            # Since we rely solely on $PSBoundParameters, we don't have access to default values for unbound parameters
            Write-Verbose 'Looking for unbound parameters with default values'

            Write-Debug 'Getting unbound parameters list'
            $UnboundParameters = (Get-Command -Name ($PSCmdlet.MyInvocation.InvocationName)).Parameters.GetEnumerator()  |
                # Find parameters that are belong to the current parameter set
            Where-Object { $_.Value.ParameterSets.Keys -contains $PsCmdlet.ParameterSetName } |
                Select-Object -ExpandProperty Key |
                # Find unbound parameters in the current parameter set
                                                Where-Object { $PSBoundParameters.Keys -notcontains $_ }

            # Even if parameter is not bound, corresponding variable is created with parameter's default value (if specified)
            Write-Debug 'Trying to get variables with default parameter value and create a new bound parameter''s'
            $tmp = $null
            foreach ($Parameter in $UnboundParameters) {
                $DefaultValue = Get-Variable -Name $Parameter -ValueOnly -Scope 0
                if (!$PSBoundParameters.TryGetValue($Parameter, [ref]$tmp) -and $DefaultValue) {
                    $PSBoundParameters.$Parameter = $DefaultValue
                    Write-Debug "Added new parameter '$Parameter' with value '$DefaultValue'"
                }
            }

            if ($Dictionary) {
                Write-Verbose 'Using external dynamic parameter dictionary'
                $DPDictionary = $Dictionary
            }
            else {
                Write-Verbose 'Using internal dynamic parameter dictionary'
                $DPDictionary = $InternalDictionary
            }

            Write-Verbose "Creating new dynamic parameter: $Name"

            # Shortcut for getting local variables
            $GetVar = {Get-Variable -Name $_ -ValueOnly -Scope 0}

            # Strings to match attributes and validation arguments
            $AttributeRegex = '^(Mandatory|Position|ParameterSetName|DontShow|HelpMessage|ValueFromPipeline|ValueFromPipelineByPropertyName|ValueFromRemainingArguments)$'
            $ValidationRegex = '^(AllowNull|AllowEmptyString|AllowEmptyCollection|ValidateCount|ValidateLength|ValidatePattern|ValidateRange|ValidateScript|ValidateSet|ValidateNotNull|ValidateNotNullOrEmpty)$'
            $AliasRegex = '^Alias$'

            Write-Debug 'Creating new parameter''s attirubutes object'
            $ParameterAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute

            Write-Debug 'Looping through the bound parameters, setting attirubutes...'
            switch -regex ($PSBoundParameters.Keys) {
                $AttributeRegex {
                    Try {
                        $ParameterAttribute.$_ = . $GetVar
                        Write-Debug "Added new parameter attribute: $_"
                    }
                    Catch {
                        $_
                    }
                    continue
                }
            }

            if ($DPDictionary.Keys -contains $Name) {
                Write-Verbose "Dynamic parameter '$Name' already exist, adding another parameter set to it"
                $DPDictionary.$Name.Attributes.Add($ParameterAttribute)
            }
            else {
                Write-Verbose "Dynamic parameter '$Name' doesn't exist, creating"

                Write-Debug 'Creating new attribute collection object'
                $AttributeCollection = New-Object -TypeName Collections.ObjectModel.Collection[System.Attribute]

                Write-Debug 'Looping through bound parameters, adding attributes'
                switch -regex ($PSBoundParameters.Keys) {
                    $ValidationRegex {
                        Try {
                            $ParameterOptions = New-Object -TypeName "System.Management.Automation.${_}Attribute" -ArgumentList (. $GetVar) -ErrorAction Stop
                            $AttributeCollection.Add($ParameterOptions)
                            Write-Debug "Added attribute: $_"
                        }
                        Catch {
                            $_
                        }
                        continue
                    }

                    $AliasRegex {
                        Try {
                            $ParameterAlias = New-Object -TypeName System.Management.Automation.AliasAttribute -ArgumentList (. $GetVar) -ErrorAction Stop
                            $AttributeCollection.Add($ParameterAlias)
                            Write-Debug "Added alias: $_"
                            continue
                        }
                        Catch {
                            $_
                        }
                    }
                }

                Write-Debug 'Adding attributes to the attribute collection'
                $AttributeCollection.Add($ParameterAttribute)

                Write-Debug 'Finishing creation of the new dynamic parameter'
                $Parameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter -ArgumentList @($Name, $Type, $AttributeCollection)

                if ($null -ne $ParameterDefaultValue) {
                    $Parameter.Value = $ParameterDefaultValue
                }

                Write-Debug 'Adding dynamic parameter to the dynamic parameter dictionary'
                $DPDictionary.Add($Name, $Parameter)
            }
        }
    }

    End {
        if (!$CreateVariables -and !$Dictionary) {
            Write-Verbose 'Writing dynamic parameter dictionary to the pipeline'
            $DPDictionary
        }
    }
}

Function Read-HostContinue {
    param (
        [Parameter(Position=0)]
        [String]$PromptTitle = '',
        [Parameter(Position=1)]
        [string]$PromptQuestion = 'Continue?',
        [Parameter(Position=2)]
        [string]$YesDescription = 'Do this.',
        [Parameter(Position=3)]
        [string]$NoDescription = 'Do not do this.',
        [Parameter(Position=4)]
        [switch]$DefaultToNo,
        [Parameter(Position=5)]
        [switch]$Force
    )
    if ($Force) {
        (-not $DefaultToNo)
        return
    }
    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", $YesDescription
    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", $NoDescription

    if ($DefaultToNo) {
        $ConsolePrompt = [System.Management.Automation.Host.ChoiceDescription[]]($no,$yes)
    }
    else {
        $ConsolePrompt = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
    }
    if (($host.ui.PromptForChoice($PromptTitle, $PromptQuestion , $ConsolePrompt, 0)) -eq 0) {
        $true
    }
    else {
        $false
    }
}

## PUBLIC MODULE FUNCTIONS AND DATA ##

Function Add-OMPAutoLoadModule {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Add-OMPAutoLoadModule.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Name,
        [Parameter(Position = 1)]
        [switch]$NoProfileUpdate
    )
    try {
        Import-OMPModule -Name $Name
        $Script:OMPProfile['AutoLoadModules'] = @($Script:OMPProfile['AutoLoadModules'] + $Name | Sort-Object -Unique)
        if (-not $NoProfileUpdate) {
            Export-OMPProfile
        }
    }
    catch {
        throw "Unable to add module $($Name)"
    }
}


Function Add-OMPPersonalFunction {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Add-OMPPersonalFunction.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Path,
        [Parameter(Position = 1)]
        [switch]$Recurse,
        [Parameter(Position = 2)]
        [switch]$NoProfileUpdate
    )
    $PathsAdded = $false
    if (Test-Path $Path) {
        if ($Recurse) {
            $Paths = @((Get-ChildItem -Path $Path -File -Filter '*.ps1').FullName)
        }
        else {
            $Paths = $($Path)
        }
        Foreach ($ScriptPath in $Paths) {
            Write-Verbose "Checking if the following is a valid candidate for being added: $ScriptPath"
            if ($Script:OMPProfile['PersonalFunctions'] -notcontains $ScriptPath){
                try {
                    Invoke-OMPPersonalFunction -Path $ScriptPath -Tag 'personalfunction'
                    $PathsAdded = $true
                    $Script:OMPProfile['PersonalFunctions'] += $ScriptPath
                }
                catch {
                    Write-Warning "Unable to load $ScriptPath"
                }
            }
        }
    }
    try {
        if ((-not $NoProfileUpdate) -and $PathsAdded) {
            Write-Verbose "Profile being updated"
            Export-OMPProfile
        }
    }
    catch {
        throw "Unable to add module $($Name)"
    }
}


Function Add-OMPPlugin {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Add-OMPPlugin.md
    #>

    [CmdletBinding()]
    param (
        [Parameter()]
        [switch]$Force,
        [Parameter()]
        [switch]$NoProfileUpdate,
        [Parameter()]
        [switch]$UpdateConfig,
        [Parameter()]
        [switch]$DebugOutput
    )
    dynamicparam {
        # Create dictionary
        $DynamicParameters = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
        $ValidPlugins = @()

        Foreach ($PPath in $Script:OMPProfile['OMPPluginRootPaths']) {
            $ValidPlugins += (Get-ChildItem $PPath -Directory).Name
        }

        $ValidPlugins = $ValidPlugins | Sort-Object | Select-Object -Unique

        $NewParamSettings = @{
            Name = 'Name'
            Position = 0
            Type = 'string'
            ValidateSet = $ValidPlugins
            HelpMessage = "The plugin to add to your profile and optionally load."
            ValueFromPipeline = $true
            ValueFromPipelineByPropertyName = $true
        }

        # Add new dynamic parameter to dictionary
        New-DynamicParameter @NewParamSettings -Dictionary $DynamicParameters

        # Return dictionary with dynamic parameters
        $DynamicParameters
    }
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }

    Process {
        # Pull in the dynamic parameters first
        New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
        $PluginPath = $null
        Foreach ($PPath in $Script:OMPProfile['OMPPluginRootPaths']) {
            if (Test-Path (Join-Path $PPath $Name)) {
                if ($null -eq $PluginPath) {
                    Write-Verbose "$($FunctionName): Loading the plugin found in $PPath"
                    $PluginPath = $PPath
                }
                else {
                    Write-Warning "$($FunctionName): More than one root plugin folder paths contain the plugin named $Name, ignoring the plugin found in $PPath"
                }
            }
        }
        if ($null -eq $PluginPath) {
            Write-Warning "Unable to locate $Name in any plugin paths!"
            return
        }
        $LoadedPlugins = $Script:OMPState['PluginsLoaded']
        if (($LoadedPlugins -notcontains $Name) -or $Force) {
            $PluginPlatform = (Get-OMPPlugin $Name).Platform
            if ($PluginPlatform -contains (Get-OMPState).Platform) {
                $Preload = $null
                $PostLoad = $null
                $LoadScript = Join-Path $PluginPath "$Name\Load.ps1"

                if (-not (Test-Path $LoadScript)) {
                    Write-Error "Unable to find the plugin load file: $LoadScript"
                }
                Write-Verbose "Executing plugin load script: $LoadScript"

                # pull in the preload and postload definitions
                $errmsg = $null
                $sb = [Scriptblock]::create(".{$(Get-Content -Path $LoadScript -Raw)}")
                Invoke-Command -NoNewScope -ScriptBlock $sb -ErrorVariable errmsg 2>$null
                if (-not ([string]::IsNullOrEmpty($errmsg)) -and $DebugOutput) {
                    Write-Warning "Unable to load plugin $Name"
                    Write-Warning "Error: $($errmsg | Select *)"
                    if (-not $Force) {
                        return
                    }
                }

                # Run preload plugin code
                $errmsg = $null
                $Preloadsb = [Scriptblock]::create(".{$Preload}")
                Invoke-Command -NoNewScope -ScriptBlock $Preloadsb -ErrorVariable errmsg 2>$null
                if (-not ([string]::IsNullOrEmpty($errmsg)) -and $Debug) {
                    Write-Warning "Unable to load plugin preload code for $Name"
                    Write-Warning "Error: $($errmsg | Select *)"
                    if (-not $Force) {
                        return
                    }
                }

                # Dot source any file in the plugin src directory of this plugin and track global functions
                $FullPluginSrcPath = Join-Path $PluginPath "$Name\src"
                Write-Verbose "Plugin $Name source file repo is $FullPluginSrcPath"

                Get-ChildItem -Path $FullPluginSrcPath -Recurse -Filter "*.ps1" -File | Sort-Object Name | ForEach-Object {
                    Write-Verbose "Dot sourcing plugin script file: $($_.Name)"
                    # First dot source the ps1
                    . $_.FullName

                    # Next look for any globally defined functions and tag them with a noteproperty to track
                    ([System.Management.Automation.Language.Parser]::ParseInput((Get-Content -Path $_.FullName -Raw), [ref]$null, [ref]$null)).FindAll({ $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $false) | Foreach-Object {
                        if (($_.Name).StartsWith('Global:')) {
                            $globalfunc = Get-ChildItem -Path "Function:\$($_.Name -replace 'Global:','')"
                            if ($GlobalFunc -ne $null) {
                                Write-Verbose "Plugin function exported into the global session: $($_.Name -replace 'Global:','')"
                                $globalfunc | Add-Member -MemberType 'NoteProperty' -Name 'ohmypsh' -Value "$Name" -Force
                            }
                        }
                    }
                }

                # Run postload plugin code
                $errmsg = $null
                $Postloadsb = [Scriptblock]::create(".{$Postload}")
                Invoke-Command -NoNewScope -ScriptBlock $Postloadsb -ErrorVariable errmsg 2>$null
                if (-not ([string]::IsNullOrEmpty($errmsg)) -and $Debug) {
                    $errmsg
                    Write-Warning "Unable to load plugin postload code for $Name"
                    Write-Warning "Error: $($errmsg | Select *)"
                    if (-not $Force) {
                        return
                    }
                }

                # Finally run any config plugin code
                if ((Test-OMPProfileSetting -Name "pluginconfig_$Name") -and (-not $UpdateConfig)) {
                    $Config = Get-OMPProfileSetting -Name "pluginconfig_$Name"
                }
                else {
                    # If not already in the profile config add the plugin config variable
                    if (Test-OMPProfileSetting -Name "pluginconfig_$Name") {
                        Set-OMPProfileSetting -Name "pluginconfig_$Name" -Value ([string]$Config)
                    }
                    else {
                        Add-OMPProfileSetting -Name "pluginconfig_$Name" -Value ([string]$Config)
                    }
                }
                $errmsg = $null
                $Configsb = [Scriptblock]::create(".{$Config}")
                Invoke-Command -NoNewScope -ScriptBlock $Configsb -ErrorVariable errmsg 2>$null
                if (-not ([string]::IsNullOrEmpty($errmsg)) -and $Debug) {
                    $errmsg
                    Write-Warning "Unable to load plugin configuration code for $Name"
                    Write-Warning "Error: $($errmsg | Select *)"
                    if (-not $Force) {
                        return
                    }
                }

                # If we made it this far then update our loaded plugins list
                $LoadedPlugins += $Name
                $Script:OMPState['PluginsLoaded'] = @($LoadedPlugins | Sort-Object -Unique)

                if (-not $NoProfileUpdate) {
                    try {
                        # update the profile plugins list as well
                        $ProfPlugins = $Script:OMPProfile['Plugins']
                        $ProfPlugins += $Name
                        $Script:OMPProfile['Plugins'] = @($ProfPlugins | Sort-Object -Unique)
                        Export-OMPProfile
                    }
                    catch {
                        throw "Unable to update or save the profile!"
                    }
                }
            }
            else {
                Write-Warning "This plugin is not supported on $((Get-OMPState).Platform) and has NOT been loaded!"
            }
        }
        else {
            Write-Output "$Name already is loaded in this session. Use the -Force parameter to load it again anyways.."
        }
    }
}


Function Add-OMPProfileSetting {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Add-OMPProfileSetting.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Name,
        [Parameter(Position = 1)]
        $Value,
        [Parameter(Position = 2)]
        [switch]$NoProfileUpdate
    )
    Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

    $ExistingSettings = @(($Script:OMPProfile).Keys)
    Write-Verbose "Existing settings: $($ExistingSettings -join ', ')"
    if ($ExistingSettings -notcontains $Name) {
        try {
            $Script:OMPProfile[$Name] = $Value
        }
        catch {
            Write-Error "Unable to add profile setting $Name"
        }

        if (-not $NoProfileUpdate) {
            try {
                Export-OMPProfile
            }
            catch {
                throw "Unable to update or save the profile!"
            }
        }
    }
    else {
        Write-Output "$Name already exists as a setting. Doing nothing."
    }
}


Function Export-OMPProfile {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Export-OMPProfile.md
    #>

    [CmdletBinding()]
    Param (
        [Parameter()]
        [string]$Path = $Script:OMPProfileExportFile
    )

    try {
        $Script:OMPProfile | ConvertTo-Json | Out-File $Path -Encoding:utf8 -Force
    }
    catch {
        throw "Unable to save $Path"
    }
}



function Get-OMPGitBranchName {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPGitBranchName.md
    #>

    $currentBranch = ''
    try {
        git branch | foreach {
            if ($_ -match "^\* (.*)") {
                $currentBranch += $matches[1]
            }
        }
    }
    catch {
        # do nothing but git likely isn't available
    }

    return $currentBranch
}



function Get-OMPGitStatus {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPGitStatus.md
    #>

    $deleted = 0
    $modified = 0
    $added = 0
    $untracked = 0

    try {
        $gitstatus = git status --porcelain --short
        $deleted = ($gitstatus | select-string '^D\s').count
        $modified = ($gitstatus | select-string '^M\s').count
        $added = ($gitstatus | select-string '^A\s').count
        $untracked = ($gitstatus | select-string '^\?\?\s').count
    }
    catch {}

    return @{
        "untracked" = $untracked
        "added" = $added
        "modified" = $modified
        "deleted" = $deleted
    }
}



function Get-OMPHostState {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPHostState.md
    #>


    [CmdletBinding()]
    param(
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    process {
    }
    end {
        $Script:HostState
        Write-Verbose "$($FunctionName): End."
    }
}



function Get-OMPIPAddress {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPIPAddress.md
    #>

    [CmdletBinding()]
    param(
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    process {
    }
    end {
        # Retreive IP address informaton from dot net core only functions (should run on both linux and windows properly)
        $NetworkInterfaces = @([System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Where-Object {($_.OperationalStatus -eq 'Up')})
        $NetworkInterfaces | Foreach-Object {
            $_.GetIPProperties() | Where-Object {$_.GatewayAddresses} | Foreach-Object {
                $Gateway = $_.GatewayAddresses.Address.IPAddressToString
                $DNSAddresses = @($_.DnsAddresses | Foreach-Object {$_.IPAddressToString})
                $_.UnicastAddresses | Where-Object {$_.Address -notlike '*::*'} | Foreach-Object {
                    New-Object PSObject -Property @{
                        IP = $_.Address
                        Prefix = $_.PrefixLength
                        Gateway = $Gateway
                        DNS = $DNSAddresses
                    }
                }
            }
        }
        Write-Verbose "$($FunctionName): End."
    }
}



function Get-OMPLoadedFunction {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPLoadedFunction.md
    #>


    [CmdletBinding()]
    param (
        [Parameter()]
        [string]$Name = '*'
    )
    Process {
        Get-ChildItem -Path "Function:\$Name" -Recurse | Where-Object { $null -ne $_.ohmypsh } | Select Name,ohmypsh
    }
}


function GET-OMPOSPlatform {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPOSPlatform.md
    #>


    [CmdletBinding()]
    param(
        [Parameter()]
        [Switch]$IncludeLinuxDetails
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    process {}
    end {
        $ThisIsCoreCLR = if ($IsCoreCLR) {$True} else {$False}
        $ThisIsLinux = if ($IsLinux) {$True} else {$False} #$Runtime::IsOSPlatform($OSPlatform::Linux)
        $ThisIsOSX = if ($IsOSX) {$True} else {$False} #$Runtime::IsOSPlatform($OSPlatform::OSX)
        $ThisIsWindows = if ($IsWindows) {$True} else {$False} #$Runtime::IsOSPlatform($OSPlatform::Windows)

        if (-not ($ThisIsLinux -or $ThisIsOSX)) {
            $ThisIsWindows = $true
        }

        if ($ThisIsLinux) {
            if ($IncludeLinuxDetails) {
                $LinuxInfo = Get-Content /etc/os-release | ConvertFrom-StringData
                $IsUbuntu = $LinuxInfo.ID -match 'ubuntu'
                if ($IsUbuntu -and $LinuxInfo.VERSION_ID -match '14.04') {
                    return 'Ubuntu 14.04'
                }
                if ($IsUbuntu -and $LinuxInfo.VERSION_ID -match '16.04') {
                    return 'Ubuntu 16.04'
                }
                if ($LinuxInfo.ID -match 'centos' -and $LinuxInfo.VERSION_ID -match '7') {
                    return 'CentOS'
                }
            }
            return 'Linux'
        }
        elseif ($ThisIsOSX) {
            return 'OSX'
        }
        elseif ($ThisIsWindows) {
            return 'Windows'
        }
        else {
            return 'Unknown'
        }
        Write-Verbose "$($FunctionName): End."
    }
}



function Get-OMPPlugin {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPPlugin.md
    #>

    [CmdletBinding()]
    [OutputType('OMP.PluginStatus')]
    param (
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [String]$Name
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."

        #Configure a default display set
        $defaultDisplaySet = 'Name','Loaded'

        #Create the default property display set
        $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet)
        $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
    }
    process {
        $AllPlugins = @()
        Foreach ($PluginPath in $Script:OMPProfile['OMPPluginRootPaths']) {
            if ([string]::IsNullOrEmpty($Name)) {
                $SearchPath = $PluginPath
                (Get-ChildItem $SearchPath -Directory).FullName | ForEach-Object {
                    $AllPlugins += $_
                }
            }
            else {
                if (Test-Path (Join-Path $PluginPath $Name)) {
                    $AllPlugins = (Join-Path $PluginPath $Name)
                }
            }
        }

        if ($AllPlugins.Count -eq 0) {
            throw "Plugin not found in any path!"
        }
        $AllPlugins | ForEach-Object {
            $pluginmanifest = Join-Path $_ 'manifest.json'
            $manifest = $null
            if (Test-Path $pluginmanifest) {
                try {
                    Write-Verbose "$($FunctionName): Manifest file found - $pluginmanifest"
                    $manifest = Get-Content -Path $pluginmanifest -Raw | ConvertFrom-Json
                    Write-Verbose "$($FunctionName): Manifest file loaded."
                }
                catch {
                    Write-Verbose "$($FunctionName): Manifest file NOT loaded."
                }
            }
            $object = [pscustomobject]@{
                Name = Split-Path $_ -Leaf
                Loaded = if ($Script:OMPState['PluginsLoaded'] -contains (Split-Path $_ -Leaf)) {$true} else {$false}
                Path = $_
                Version = $manifest.Version
                Description = $manifest.Description
                Platform = $manifest.Platform
            }
            $object.PSTypeNames.Insert(0,'OMP.PluginStatus')
            $object | Add-Member MemberSet PSStandardMembers $PSStandardMembers

            $object
        }
    }
}


function Get-OMPPowerShellProfile {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPPowerShellProfile.md
    #>


    [CmdletBinding()]
    param(
        [Parameter()]
        [ValidateSet('AllUsersAllHosts','AllUsersCurrentHost','CurrentUserAllHosts','CurrentUserCurrentHost')]
        [string]$ProfileType = 'CurrentUserCurrentHost'
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    end {
        if (Test-Path $PROFILE.$ProfileType) {
            Get-Content $PROFILE.$ProfileType
        }
        else {
            Write-Warning "$($FunctionName): Profile does not exist - $($PROFILE.$ProfileType)"
        }
        Write-Verbose "$($FunctionName): End."
    }
}



function Get-OMPPowerShellProfileState {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPPowerShellProfileState.md
    #>


    [CmdletBinding()]
    param(
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."

        $ProfileTypes = @('AllUsersAllHosts','AllUsersCurrentHost','CurrentUserAllHosts','CurrentUserCurrentHost')
    }
    end {
        $order = 0
        Foreach ($PType in $Profiletypes) {
            $order++
            New-Object -TypeName psobject -Property @{
                Name = $PType
                Exists = if (test-path $PROFILE.$Ptype) {$true} else {$false}
                Path = $PROFILE.$Ptype
                Order = $order
            } | Select Order, Name, Exists, Path
        }
        Write-Verbose "$($FunctionName): End."
    }
}



Function Get-OMPProfilePath {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPProfilePath.md
    #>

    [CmdletBinding()]
    param ()

    $Script:OMPProfileExportFile
}


Function Get-OMPProfileSetting {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPProfileSetting.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [ValidateScript({
            (($Script:OMPProfile).Keys -contains $_ ) -or ([string]::IsNullOrEmpty($_))
        })]
        [String]$Name
    )
    process {
        if ([string]::IsNullOrEmpty($Name)) {
            $Script:OMPProfile
        }
        else {
            $Script:OMPProfile[$Name]
        }
    }
}


Function Get-OMPPromptColor {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPPromptColor.md
    #>

    [CmdletBinding()]
    param ()

    [psobject]@{
        BackgroundColor = $Host.UI.RawUI.BackgroundColor
        ForegroundColor = $Host.UI.RawUI.ForegroundColor
        ErrorForegroundColor = $Host.PrivateData.ErrorForegroundColor
        WarningForegroundColor = $Host.PrivateData.WarningForegroundColor
        DebugForegroundColor = $Host.PrivateData.DebugForegroundColor
        VerboseForegroundColor = $Host.PrivateData.VerboseForegroundColor
        ProgressForegroundColor = $Host.PrivateData.ProgressForegroundColor
        ErrorBackgroundColor = $Host.PrivateData.ErrorBackgroundColor
        WarningBackgroundColor  = $Host.PrivateData.WarningBackgroundColor
        DebugBackgroundColor = $Host.PrivateData.DebugBackgroundColor
        VerboseBackgroundColor = $Host.PrivateData.VerboseBackgroundColor
        ProgressBackgroundColor = $Host.PrivateData.ProgressBackgroundColor
    }
}


function Get-OMPState {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPState.md
    #>


    [CmdletBinding()]
    param(
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    process {}
    end {
        $Script:OMPState
        Write-Verbose "$($FunctionName): End."
    }
}



function Get-OMPSystemUpTime {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPSystemUpTime.md
    #>


    [CmdletBinding()]
    param(
        [switch]$FromSleep
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
        function Test-EventLogSource {
            param(
                [Parameter(Mandatory = $true)]
                [string] $SourceName
            )
            try {
                [System.Diagnostics.EventLog]::SourceExists($SourceName)
            }
            catch {
                $false
            }
        }
    }
    process {}
    end {
        switch ( Get-OMPOSPlatform -ErrorVariable null ) {
            'Linux' {
                # Add me!
            }
            'OSX' {
                # Add me!
            }
            Default {
                if (-not $FromSleep) {
                    $os = Get-WmiObject win32_operatingsystem
                    $Uptime = (Get-Date) - ($os.ConvertToDateTime($os.lastbootuptime))
                }
                elseif (Test-EventLogSource 'Microsoft-Windows-Power-Troubleshooter') {
                    try {
                        $LastPowerEvent = (Get-EventLog -LogName system -Source 'Microsoft-Windows-Power-Troubleshooter' -Newest 1 -ErrorAction:Stop).TimeGenerated
                    }
                    catch {
                        $error.Clear()
                    }
                    if ($LastPowerEvent -ne $null) {
                        $Uptime = ( (Get-Date) - $LastPowerEvent )
                    }
                }
                if ($Uptime -ne $null) {
                    $Display = "" + $Uptime.Days + " days / " + $Uptime.Hours + " hours / " + $Uptime.Minutes + " minutes"
                    Write-Output $Display
                }
            }
        }
        Write-Verbose "$($FunctionName): End."
    }
}



function Get-OMPTheme {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Get-OMPTheme.md
    #>


    [CmdletBinding()]
    [OutputType('OMP.ThemeStatus')]
    param (
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [ValidateScript({
            (@((Get-ChildItem (Join-Path $Script:ModulePath 'Themes') -File -Filter '*.ps1').Name | ForEach-Object {$_ -replace '.ps1',''}) -contains $_) -or ([string]::IsNullOrEmpty($_))
        })]
        [String]$Name
    )
    Begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."

        #Configure a default display set
        $defaultDisplaySet = 'Name','Loaded'

        #Create the default property display set
        $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet)
        $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
    }
    Process {
        if ([string]::IsNullOrEmpty($Name)) {
            $Themes = @((Get-ChildItem (Join-Path $Script:ModulePath 'Themes') -File -Filter '*.ps1').Name | ForEach-Object {$_ -replace '.ps1',''})
        }
        else {
            $Themes = @((Get-ChildItem (Join-Path $Script:ModulePath "Themes\$Name.ps1") -File -Filter '*.ps1').Name | ForEach-Object {$_ -replace '.ps1',''})
        }
        $Themes | ForEach-Object {
            $ThemePath = Join-Path $Script:ModulePath "Themes\$($_).ps1"
            $object = New-Object -TypeName PSObject -Property @{
                'Name' = $_
                'Loaded' = if ($Script:OMPProfile['Theme'] -eq $_) {$true} else {$false}
                'Path' = $ThemePath
                'Content' = Get-Content $ThemePath
            }

            $object.PSTypeNames.Insert(0,'OMP.ThemeStatus')
            $object | Add-Member MemberSet PSStandardMembers $PSStandardMembers

            $object
        }
    }
    End {
        Write-Verbose "$($FunctionName): End."
    }
}


Function Import-OMPModule {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Import-OMPModule.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string[]]$Name,
        [Parameter()]
        [string]$Prefix
    )
    Begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."

        $AllModules = @()
        $ImportSplat = @{}
        if (-not [string]::IsNullOrEmpty($Prefix)) {
            $ImportSplat.Prefix = $Prefix
        }
        if ($Force) {
            $ImportSplat.Force = $true
        }
    }
    Process {
        $AllModules += $Name
    }
    End {
        Foreach ($Module in $AllModules) {
            if ( $null -eq (Get-Module $Module -ListAvailable) ) {
                if ($Script:OMPProfile['AutoInstallModules']) {
                    Write-Verbose "$($FunctionName): Attempting to install missing module: $($Module)"
                    try {
                        Import-Module PowerShellGet -Force
                        $InstallModuleSplat = $Script:OMPProfile['OMPModuleInstallSplat']
                        $null = Install-Module $Module @InstallModuleSplat
                        Write-Verbose "$($FunctionName): Module Installed - $($Module)"
                    }
                    catch {
                        throw "Unable to find or install the following module requirement: $($Module)"
                    }
                }
                else {
                    throw "$($Module) was not found and automatic installation of modules is disabled in this profile!"
                }
            }

            # If we made it this far and the module isn't loaded, try to do so now. We have to import globaly for it to show up in the calling user's session.
            if (-not (get-module $Module)) {
                Write-Verbose "$($FunctionName): Attempting to import module - $Module"
                Import-Module $Module -Global -force @ImportSplat
            }
            else {
                Write-Verbose "$($FunctionName): $Module is already loaded"
                return
            }

            # check if it loaded properly
            if (-not (get-module $Module)) {
                throw "$($Module) was not able to load!"
            }
            else {
                Write-Verbose "$($FunctionName): Module Imported - $Module"
            }
        }
    }
}


Function Import-OMPProfile {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Import-OMPProfile.md
    #>

    [CmdletBinding()]
    Param (
        [Parameter()]
        [string]$Path = $Script:OMPProfileExportFile
    )

    try {
        $LoadedProfile = Get-Content $Path | ConvertFrom-Json
    }
    catch {
        throw "Unable to load $Path"
    }

    $ProfileSettings = ($LoadedProfile | Get-Member -Type 'NoteProperty').Name
    ForEach ($Key in $ProfileSettings) {
        if (@($Script:OMPProfile.Keys) -contains $Key) {
            Write-Verbose "Updating profile setting '$key' from $Path"
            $Script:OMPProfile[$Key] = $LoadedProfile.$Key
        }
        else {
            Write-Verbose "Adding profile setting '$key' from $Path"
            ($Script:OMPProfile).$Key = $LoadedProfile.$Key
        }
    }
    $MissingSettings = @($Script:OMPProfile.Keys | Where-Object {$ProfileSettings -notcontains $_})
    if ($MissingSettings.Count -gt 0) {
        Write-Verbose "There were $($MissingSettings.Count) settings missing from the saved profile. Re-exporting to bring profile up to date."
        try {
            Export-OMPProfile -Path $Script:OMPProfileExportFile
        }
        catch {
            throw "Unable to export profile to $($Script:OMPProfileExportFile)"
        }
    }
}



Function Invoke-OMPPluginShutdown {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Invoke-OMPPluginShutdown.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [string]$Name
    )

    Begin {
        Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        Write-Verbose "Attempting to shutdown the plugin $Name"
    }

    Process {
        Foreach ($Plugin in (Get-OMPPlugin -Name $Name | Where {$_.Loaded})) {
            $LoadScript = Join-Path $Plugin.Path "Load.ps1"
            $Shutdown = $null
            if (-not (Test-Path $LoadScript)) {
                Write-Error "Unable to find the plugin load file: $LoadScript"
                return
            }

            Write-Verbose "Executing plugin load script: $LoadScript"
            # pull in the entire load script
            $errmsg = $null
            $sb = [Scriptblock]::create(".{$(Get-Content -Path $LoadScript -Raw)}")
            Invoke-Command -NoNewScope -ScriptBlock $sb -ErrorVariable errmsg 2>$null
            if (-not ([string]::IsNullOrEmpty($errmsg))) {
                Write-Warning "Unable to load plugin $($Plugin.Name)"
                Write-Warning "Error: $($errmsg | Select *)"
                return
            }

            # Run shutdown plugin code
            $errmsg = $null
            if ($Shutdown -ne $null) {
                $Shutdownsb = [Scriptblock]::create(".{$Shutdown}")
                Invoke-Command -NoNewScope -ScriptBlock $Shutdownsb -ErrorVariable errmsg 2>$null
                if (-not ([string]::IsNullOrEmpty($errmsg))) {
                    Write-Warning "Unable to run shutdown plugin code for $($Plugin.Name)"
                    Write-Warning "Error: $($errmsg | Select *)"
                    return
                }
            }
        }
    }
}


Function New-OMPPlugin {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/New-OMPPlugin.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Name,
        [Parameter()]
        [string]$Path
    )
    if ($script:ThisModuleLoaded -eq $true) {
        Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
    }
    $FunctionName = $MyInvocation.MyCommand.Name
    Write-Verbose "$($FunctionName): Begin."

    $TemplatePath = Join-Path $Script:ModulePath 'templates\plugin'
    if ([string]::IsNullOrEmpty($Path)) {
        $PluginDestPath = Join-Path $Script:ModulePath "plugins\$Name"
    }
    else {
        if (Test-Path $Path) {
            $PluginDestPath = Join-Path $Path $Name

            if ((Get-OMPProfileSetting).OMPPluginRootPaths -notcontains $Path) {
                Write-Warning "$($FunctionName): $Path exists but is not in the OMPPluginRootPaths list for your profile. This plugin will be created regardless but will not be usable."
            }
        }
        else {
            throw "$Path does not exist!"
        }
    }

    Write-Verbose "$($FunctionName): New Plugin Path = $PluginDestPath"
    if (Test-Path $TemplatePath) {
        if (-not (Test-Path $PluginDestPath)) {
            $null = Copy-Item -Path $TemplatePath -Destination $PluginDestPath -Recurse
            Write-Output "The following plugin template has been created: $PluginDestPath"
            Write-Output "Modify the $PluginDestPath\src\Plugin.ps1 file to suit your needs."
            Write-Output "When ready to do so, test your plugin with Add-OMPPlugin -Name $Name -NoProfileUpdate"
        }
        else {
            Write-Error "The plugin name already exists: $PluginDestPath"
        }
    }
    else {
        Write-Error "The source plugin template path doesn't exist: $TemplatePath"
    }
}


Function New-OMPPluginManifest {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/New-OMPPluginManifest.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Name,
        [Parameter()]
        [string]$Path,
        [Parameter()]
        [string]$Version = '0.0.1',
        [Parameter()]
        [string]$Description = ''

    )
    if ($script:ThisModuleLoaded -eq $true) {
        Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
    }
    $FunctionName = $MyInvocation.MyCommand.Name
    Write-Verbose "$($FunctionName): Begin."

    if ([string]::IsNullOrEmpty($Path)) {
        $ManifestFile = Join-Path $Script:ModulePath "plugins\$Name\manifest.json"
    }
    else {
        if (Test-Path $Path) {
            if (-not $Path.EndsWith('manifest.json')) {
                $ManifestFile = Join-Path $Path 'manifest.json'
            }
            else {
                $ManifestFile = $Path
            }
        }
        else {
            throw "$Path does not exist!"
        }
    }

    Write-Verbose "$($FunctionName): Manifest file to output = $Manifestfile"

    try {
        [psobject]@{
            Name = $Name
            Version = $Version
            Description = $Description
        } | ConvertTo-Json | Out-File $ManifestFile -Encoding:utf8
    }
    catch {
        throw
    }

}



Function Optimize-OMPProfile {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Optimize-OMPProfile.md
    #>

    [CmdletBinding()]
    Param()
    if ((Test-OMPIsElevated) -and ((Get-OMPOSPlatform) -eq 'Windows')) {
        Write-Output 'Optimizing assemblies for PowerShell profile.'
        $env:path = (@($env:path -split ';') + [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() | Sort-Object -Unique) -join ';'
        [AppDomain]::CurrentDomain.GetAssemblies() | ForEach-Object {
            if (-not $_.location) {
                continue
            }

            $Name = Split-Path $_.location -leaf
            Write-Output "NGENing : $Name"
            ngen install $_.location | ForEach-Object {"`t$_"}
        }
    }
    else {
        Write-Warning "Not able to optimize assemblies either because this prompt is not eleveted or the platform is not Windows."
    }
}


Function Remove-OMPAutoLoadModule {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Remove-OMPAutoLoadModule.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Name,
        [Parameter(Position = 1)]
        [switch]$NoProfileUpdate
    )
    try {
        Remove-OMPModule -Name $Name -ErrorAction:SilentlyContinue
        $Script:OMPProfile['AutoLoadModules'] = @($Script:OMPProfile['AutoLoadModules'] | Where-Object {$_ -ne $Name} | Sort-Object -Unique)
        if (-not $NoProfileUpdate) {
            Export-OMPProfile
        }
    }
    catch {
        # Do nothing
    }
}


Function Remove-OMPModule {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Remove-OMPModule.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        [string[]]$Name,
        [Parameter(Position = 1)]
        [switch]$PluginSafe
    )
    Begin {
        Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        $AllModules = @()
        $PluginSafeArg = @{}
        if ($PluginSafe) {
            $PluginSafeArg.PluginSafe = $true
        }

    }
    Process {
        $AllModules += (Get-Module $Name).Name
    }
    End {
        Foreach ($Module in $AllModules) {
            # Recursively remove dependant modules first...
            $ModulesDependOnMe = @(Get-Module | Where {$_.RequiredModules -contains $Module})
            if ($ModulesDependOnMe.Count -gt 0) {
                Write-Verbose "Found $($ModulesDependOnMe.Count) other modules dependant upon $Module"
                $ModulesDependOnMe | ForEach-Object {
                    Write-Verbose "Recursively attempting to remove $($_) first..."
                    Remove-OMPModule -Name $_ @PluginSafeArg
                }
            }

            # if pluginsafe removal then only remove modules new since OMP started and not in our autoload module list.
            if ($PluginSafe) {
                $WasAlreadyLoaded = ($Script:OMPState['ModulesAlreadyLoaded'] -contains $Module)
                $IsAutoLoaded = ($Script:OMPProfile['AutoLoadModules' -contains $Module])

                if (-not ($WasAlreadyLoaded -or $IsAutoLoaded)) {
                    try {
                        Write-Verbose "Attempting to remove module: $Module"
                        Remove-Module -Name $Module -Force
                    }
                    catch {
                        throw "Unable to remove module $($Name)"
                    }
                }
                else {
                    Write-Output "Refraining from unloading module as it is defined for autoloading in the profile or was loaded before OhMyPsh started."
                }
            }
            else {
                try {
                    Write-Verbose "Attempting to remove module: $Module"
                    Remove-Module -Name $Module -Force
                }
                catch {
                    throw "Unable to remove module $($Name)"
                }
            }
        }
    }
}


Function Remove-OMPPersonalFunction {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Remove-OMPPersonalFunction.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Path,
        [Parameter(Position = 1)]
        [switch]$NoProfileUpdate
    )
    try {
        $Script:OMPProfile['PersonalFunctions'] = @($Script:OMPProfile['PersonalFunctions'] | Where-Object {$_ -ne $Path} | Sort-Object -Unique)
        if (-not $NoProfileUpdate) {
            Export-OMPProfile
        }
    }
    catch {
        throw "Unable to remove personal function path: $Path"
    }
}


Function Remove-OMPPlugin {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Remove-OMPPlugin.md
    #>

    [CmdletBinding()]
    param (
        [Parameter()]
        [switch]$Force,
        [Parameter()]
        [switch]$NoProfileUpdate
    )
    dynamicparam {
        # Create dictionary
        $DynamicParameters = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

        $NewParamSettings = @{
            Name = 'Name'
            Position = 0
            Type = 'string'
            HelpMessage = 'The plugin to remove.'
            ValueFromPipeline = $true
            ValueFromPipelineByPropertyName = $true
        }
        $NewParamSettings.ValidateSet = @($Script:OMPState['PluginsLoaded'])
        if ((@($Script:OMPState['PluginsLoaded']).Count -gt 0) -and (-not $force)) {
            $NewParamSettings.ValidateSet = (Get-OMPProfileSetting).Plugins
        }

        # Add new dynamic parameter to dictionary
        New-DynamicParameter @NewParamSettings -Dictionary $DynamicParameters

        # Return dictionary with dynamic parameters
        $DynamicParameters
    }
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    process {
        # Pull in the dynamic parameters first
        New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters

        $LoadedPlugins = $Script:OMPState['PluginsLoaded']

        if (-not [string]::IsNullOrEmpty($Name)) {
            if ((@($Script:OMPState['PluginsLoaded']) -contains $Name) -or $Force) {
                $Unload = $null
                $PluginPath = (Get-OMPPlugin | Where {$_.Name -eq $Name}).Path
                $UnloadScript = Join-Path $PluginPath 'Load.ps1'

                if (Test-Path $UnloadScript) {
                    Write-Verbose "Executing plugin unload script: $UnloadScript"

                    # pull in the unload definition
                    $sb = [Scriptblock]::create(".{$(Get-Content -Path $UnloadScript -Raw)}")
                    Invoke-Command -NoNewScope -ScriptBlock $sb -ErrorVariable errmsg 2>$null
                    if (-not ([string]::IsNullOrEmpty($errmsg))) {
                        Write-Warning "Unable to unload plugin - $Name"
                        Write-Warning "Error: $($errmsg | Select *)"
                        throw
                    }

                    # Run unload plugin code
                    $Unloadsb = [Scriptblock]::create(".{$Unload}")
                    Invoke-Command -NoNewScope -ScriptBlock $Unloadsb -ErrorVariable errmsg 2>$null
                    if (-not ([string]::IsNullOrEmpty($errmsg))) {
                        Write-Warning "Unable to unload plugin - $Name"
                        Write-Warning "Error: $($errmsg | Select *)"
                        throw
                    }
                }
                else {
                    Write-Verbose "No unload file found for plugin - $Name"
                }

                # If we made it this far then update our loaded plugins list to remove the plugin
                $Script:OMPState['PluginsLoaded'] = @($LoadedPlugins | Where-Object {$_ -ne $Name} | Sort-Object -Unique)

                if (-not $NoProfileUpdate) {
                    try {
                        $Script:OMPProfile['Plugins'] = @($Script:OMPProfile['Plugins'] | Where-Object {$_ -ne $Name} | Sort-Object -Unique)
                        Export-OMPProfile
                    }
                    catch {
                        throw "Unable to update or save the profile!"
                    }
                }
            }
            else {
                Write-Output "$Name is not loaded in this session. Use the -Force parameter to try to unload it regardless."
            }
        }
    }
}


Function Remove-OMPProfileSetting {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Remove-OMPProfileSetting.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Name,
        [Parameter(Position = 1)]
        [switch]$NoProfileUpdate
    )
    Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

    $ExistingSettings = @(($Script:OMPProfile).Keys)

    if (($ExistingSettings -contains $Name) -and ($Script:OMPProfileCoreSettings -notcontains $Name)) {
        try {
            ($Script:OMPProfile).Remove($Name)
        }
        catch {
            Write-Error "Unable to remove profile setting $Name"
        }

        if (-not $NoProfileUpdate) {
            try {
                Export-OMPProfile
            }
            catch {
                throw "Unable to update or save the profile!"
            }
        }
    }
    else {
        Write-Output "$Name either doesn't exist or is a core profile property"
    }
}


function Reset-OMPConsoleOverride {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Reset-OMPConsoleOverride.md
    #>


    [CmdletBinding()]
    param(
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."

        function linksto($path, $target) {
            if(!(isshortcut $path)) { return $false }

            $path = "$(resolve-path $path)"

            $shell = new-object -com wscript.shell -strict
            $shortcut = $shell.createshortcut($path)

            $result = $shortcut.targetpath -eq $target
            [Runtime.Interopservices.Marshal]::ReleaseComObject($shortcut) > $null
            return $result
        }

        function isshortcut($path) {
            if(!(test-path $path)) { return $false }
            if($path -notmatch '\.lnk$') { return $false }
            return $true
        }

        # based on code from coapp:
        # https://github.com/coapp/coapp/tree/master/toolkit/Shell
        $cs = @"
        using System;
        using System.Runtime.InteropServices;
        using System.Runtime.InteropServices.ComTypes;
        namespace concfg {
            public static class Shortcut {
                public static void RmProps(string path) {
                    var NT_CONSOLE_PROPS_SIG = 0xA0000002;
                    var STGM_READ = 0;
                    var lnk = new ShellLinkCoClass();
                    var data = (IShellLinkDataList)lnk;
                    var file = (IPersistFile)lnk;
                    file.Load(path, STGM_READ);
                    data.RemoveDataBlock(NT_CONSOLE_PROPS_SIG);
                    file.Save(path, true);
                    Marshal.ReleaseComObject(data);
                    Marshal.ReleaseComObject(file);
                    Marshal.ReleaseComObject(lnk);
                }
            }
            [ComImport, Guid("00021401-0000-0000-C000-000000000046")]
            class ShellLinkCoClass { }
            [ComImport,
            InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
            Guid("45e2b4ae-b1c3-11d0-b92f-00a0c90312e1")]
            interface IShellLinkDataList {
                void _VtblGap1_2(); // AddDataBlock, CopyDataBlock
                [PreserveSig]
                Int32 RemoveDataBlock(UInt32 dwSig);
                void _VtblGap2_2(); // GetFlag, SetFlag
            }
        }
"@


        add-type -typedef $cs -lang csharp

        function rmprops($path) {
            if(!(isshortcut $path)) { return $false }

            $path = "$(resolve-path $path)"
            try { [concfg.shortcut]::rmprops($path) }
            catch [UnauthorizedAccessException] {
                return $false
            }
            $true
        }

        $pspath = "$pshome\powershell.exe"
        $pscorepath = "$pshome\pwsh.exe"

        function cleandir($dir) {
            if(!(test-path $dir)) { return }

            gci $dir | % {
                if($_.psiscontainer) { cleandir $_.fullname }
                else {
                    $path = $_.fullname
                    if((linksto $path $pspath) -or (linksto $path $pscorepath)) {
                        if(!(rmprops $path)) {
                            write-host "warning: admin permission is required to remove console props from $path" -f darkyellow
                        }
                    }
                }
            }
        }
    }
    process {
    }
    end {
        if(test-path hkcu:console) {
            gci hkcu:console | % {
                write-host "removing $($_.name)"
                rm "registry::$($_.name)"
            }
        }
        $dirs = @(
            "~\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar",
            "~\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell",
            "\ProgramData\Microsoft\Windows\Start Menu\Programs"
        )

        $dirs | % {    cleandir $_ }
        Write-Verbose "$($FunctionName): End."
    }
}



Function Restore-OMPConsoleColor {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Restore-OMPConsoleColor.md
    #>

    [CmdletBinding()]
    param ()
    Write-Verbose 'Restoring original console colors (this does not include psreadline configurations)'
    $OriginalColors = $Script:HostState['colors']

    Set-OMPConsoleColor @OriginalColors
}


Function Restore-OMPConsolePrompt {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Restore-OMPConsolePrompt.md
    #>

    [CmdletBinding()]
    param ()
    #if ($null -ne $Script:OldPrompt) {
        Write-Verbose 'Restoring original Prompt function'
        Set-Item Function:\prompt $Script:HostState['Prompt']
    #}
}


Function Restore-OMPConsoleTitle {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Restore-OMPConsoleTitle.md
    #>

    [CmdletBinding()]
    param ()
    Write-Verbose 'Restoring original console title'
    $Global:Host.UI.RawUI.WindowTitle = $Script:HostState['Title']
}


Function Restore-OMPOriginalAlias {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Restore-OMPOriginalAlias.md
    #>

    [CmdletBinding()]
    param ()
    # I cannot figure out a way to import these automatically back into the users session when the module unloads
    # so for now tell the user how to do so themselves if so desired.
    $Path = $Script:HostState['Aliases']
    if ((Test-Path $Path)) {
        Write-Output ''
        Write-Output "Original aliases stored in $Path"
        Write-Output 'To restore these into your session run the following: '
        Write-Output ''
        Write-Output ". $Path"
        Write-Output ''
    }
}


Function Restore-OMPOriginalPSDefaultParameter {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Restore-OMPOriginalPSDefaultParameter.md
    #>

    [CmdletBinding()]
    param ()
    Write-Verbose 'Restoring original PSDefaultParameters variable'
    $Global:PSDefaultParameterValues = $Script:HostState['PSDefaultParameterValues'].Clone()
}


Function Restore-OMPOriginalTabCompletion {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Restore-OMPOriginalTabCompletion.md
    #>

    [CmdletBinding()]
    param ()
    Write-Verbose 'Restoring original TabExpansion function'
    Set-Item function:\TabExpansion $Script:HostState['TabExpansion']

    Write-Verbose 'Restoring original TabExpansion2 function'
    Set-Item function:\TabExpansion2 $Script:HostState['TabExpansion2']
}


Function Restore-OMPPSReadline {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Restore-OMPPSReadline.md
    #>

    [CmdletBinding()]
    param ()
    Write-Verbose 'Restoring original psreadline settings and colors'
    if ($null -ne $Script:PSReadlineState) {
        $TokenKinds = @(
            'Comment',
            'Keyword',
            'String',
            'Operator',
            'Variable',
            'Command',
            'Parameter',
            'Type',
            'Number',
            'Member')
        $PSReadlineSplat = @{}
        Foreach ($ReadlineOption in ($Script:PSReadlineState | Get-Member -MemberType:Property).Name) {
            if ($ReadlineOption -match '^(.*)(ForegroundColor|BackgroundColor)$') {
                $Token = $Matches[1]
                $ParamName = $Matches[2]
                if ($TokenKinds -contains $Token) {
                    Write-Output "Restoring $ParamName for $Token to $(($Script:PSReadlineState).$ReadlineOption)"
                    $Psreadlinesplat = @{
                        TokenKind = $Token
                        $ParamName = ($Script:PSReadlineState).$ReadlineOption
                    }

                    Set-PSReadlineOption @Psreadlinesplat
                }
            }
            else {
                $PSReadlineSplat.$ReadlineOption = ($Script:PSReadlineState).$ReadlineOption
            }
        }

        Set-PSReadlineOption @PSReadlineSplat
    }

    Set-OMPConsoleColor @OriginalColors
}


function Set-OMPConsoleColor {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Set-OMPConsoleColor.md
    #>


    [CmdletBinding()]
    param(
        $BackgroundColor,
        $ForegroundColor,
        $ErrorForegroundColor,
        $WarningForegroundColor,
        $DebugForegroundColor,
        $VerboseForegroundColor,
        $ProgressForegroundColor,
        $ErrorBackgroundColor,
        $WarningBackgroundColor,
        $DebugBackgroundColor,
        $VerboseBackgroundColor,
        $ProgressBackgroundColor
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
        $PsreadlineIsLoaded = if (get-module psreadline) {$true} else {$false}
    }
    process {
        if ($PsreadlineIsLoaded) {
            Write-Verbose "$($FunctionName): Psreadline is loaded, setting psreadline options."
            $PSReadlineOptions = Get-PSReadlineOption
        }
        else {
            Write-Verbose "$($FunctionName): Psreadline is not loaded, setting default host console colors."
        }
        if ($null -ne $BackgroundColor) {
            Write-Verbose "$($FunctionName): Setting the BackgroundColor"
            if ($PsreadlineIsLoaded) {
                $PSReadlineOptions.CommandBackgroundColor = $BackgroundColor
            }
            $Host.UI.RawUI.BackgroundColor = [System.ConsoleColor]$BackgroundColor
        }
        if ($null -ne $ForegroundColor) {
            Write-Verbose "$($FunctionName): Setting the ForegroundColor"
            if ($PsreadlineIsLoaded) {
                $PSReadlineOptions.CommandForegroundColor = $ForegroundColor
            }
            $Host.UI.RawUI.ForegroundColor = [System.ConsoleColor]$ForegroundColor
        }
        if (($host.PrivateData | get-member -Type:Property).Count -gt 0) {
            if ($null -ne $ErrorForegroundColor) {
                Write-Verbose "$($FunctionName): Setting the ErrorForegroundColor"
                if ($PsreadlineIsLoaded) {
                    $PSReadlineOptions.ErrorForegroundColor = $ErrorForegroundColor
                }
                $Host.PrivateData.ErrorForegroundColor = [System.ConsoleColor]$ErrorForegroundColor
            }
            if ($null -ne $WarningForegroundColor) {
                Write-Verbose "$($FunctionName): Setting the WarningforegroundColor"
                #if ($PsreadlineIsLoaded) {
                # $PSReadlineOptions.WarningForegroundColor = $WarningForegroundColor
                #}
                $Host.PrivateData.WarningForegroundColor = [System.ConsoleColor]$WarningForegroundColor
            }
            if ($null -ne $DebugForegroundColor) {
                Write-Verbose "$($FunctionName): Setting the DebugForegroundColor"
                #if ($PsreadlineIsLoaded) {
                # $PSReadlineOptions.DebugForegroundColor = $DebugForegroundColor
                #}
                $Host.PrivateData.DebugForegroundColor = [System.ConsoleColor]$DebugForegroundColor
            }
            if ($null -ne $VerboseForegroundColor) {
                Write-Verbose "$($FunctionName): Setting the VerboseForegroundColor"
                #if ($PsreadlineIsLoaded) {
                # $PSReadlineOptions.VerboseForegroundColor = $VerboseForegroundColor
                #}
                $Host.PrivateData.VerboseForegroundColor = [System.ConsoleColor]$VerboseForegroundColor
            }
            if ($null -ne $ProgressForegroundColor) {
                Write-Verbose "$($FunctionName): Setting the ProgressForegroundColor"
               # if ($PsreadlineIsLoaded) {
               # $PSReadlineOptions.ProgressForegroundColor = $ProgressForegroundColor
               # }
                $Host.PrivateData.ProgressForegroundColor = [System.ConsoleColor]$ProgressForegroundColor
            }
            if ($null -ne $ErrorBackgroundColor) {
                Write-Verbose "$($FunctionName): Setting the ErrorBackgroundColor"
                #if ($PsreadlineIsLoaded) {
                # $PSReadlineOptions.ErrorBackgroundColor = $ErrorBackgroundColor
                #}
                $Host.PrivateData.ErrorBackgroundColor = [System.ConsoleColor]$ErrorBackgroundColor
            }
            if ($null -ne $WarningBackgroundColor) {
                Write-Verbose "$($FunctionName): Setting the WarningBackgroundColor"
                #if ($PsreadlineIsLoaded) {
                # $PSReadlineOptions.WarningBackgroundColor = $WarningBackgroundColor
                #}
                $Host.PrivateData.WarningBackgroundColor = [System.ConsoleColor]$WarningBackgroundColor
            }
            if ($null -ne $DebugBackgroundColor) {
                Write-Verbose "$($FunctionName): Setting the DebugBackgroundColor"
                #if ($PsreadlineIsLoaded) {
                # $PSReadlineOptions.DebugBackgroundColor = $DebugBackgroundColor
                #}
                $Host.PrivateData.DebugBackgroundColor = [System.ConsoleColor]$DebugBackgroundColor
            }
            if ($null -ne $VerboseBackgroundColor) {
                Write-Verbose "$($FunctionName): Setting the VerboseBackgroundColor"
                #if ($PsreadlineIsLoaded) {
                # $PSReadlineOptions.VerboseBackgroundColor = $VerboseBackgroundColor
                #}
                $Host.PrivateData.VerboseBackgroundColor = [System.ConsoleColor]$VerboseBackgroundColor
            }
            if ($null -ne $ProgressBackgroundColor) {
                Write-Verbose "$($FunctionName): Setting the ProgressBackgroundColor"
                #if ($PsreadlineIsLoaded) {
                # $PSReadlineOptions.ProgressBackgroundColor = $ProgressBackgroundColor
                #}
                $Host.PrivateData.ProgressBackgroundColor = [System.ConsoleColor]$ProgressBackgroundColor
            }
        }
    }
    end {
        Write-Verbose "$($FunctionName): End."
    }
}



function Set-OMPGitOutput {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Set-OMPGitOutput.md
    #>


    [CmdletBinding()]
    param (
        [Parameter(Position = 0)]
        [ValidateSet('psgit','posh-git','script')]
        [string]$Name = 'script'
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    end {
        switch ($Name) {
            'psgit' {
                Write-Verbose "$($FunctionName): Setting to psgit, attempting to unload posh-git if loaded."
                Remove-OMPAutoLoadModule 'posh-git' -ErrorAction:SilentlyContinue
                if (get-module 'posh-git') { Remove-Module 'posh-git' -ErrorAction:SilentlyContinue }

                try {
                    Import-OMPModule 'psgit'
                    Add-OMPAutoLoadModule 'psgit'
                    Set-OMPProfileSetting -Name:OMPGitOutput -Value:$Name
                }
                catch {
                    Write-Warning "$($FunctionName): Unable to load psgit module! Leaving current OMP git output setting in place."
                }
            }
            'posh-git' {
                Write-Verbose "$($FunctionName): Setting to posh-git, attempting to unload psgit if loaded."
                Remove-OMPAutoLoadModule 'psgit' -ErrorAction:SilentlyContinue
                if (get-module 'psgit') { Remove-Module 'psgit' -ErrorAction:SilentlyContinue }

                try {
                    Import-OMPModule 'posh-git'
                    Add-OMPAutoLoadModule 'posh-git'
                    Set-OMPProfileSetting -Name:OMPGitOutput -Value:$Name
                }
                catch {
                    Write-Warning "$(FunctionName): Unable to load posh-git module! Leaving current OMP git output setting in place."
                }
            }
            Default {
                Write-Verbose "$($FunctionName): Setting to script, leaving git modules as they are"
                Remove-OMPAutoLoadModule 'psgit'
                Remove-OMPAutoLoadModule 'posh-git'
                if (get-module 'psgit') { Remove-Module 'psgit' -ErrorAction:SilentlyContinue }
                if (get-module 'posh-git') { Remove-Module 'posh-git' -ErrorAction:SilentlyContinue }
                Set-OMPProfileSetting -Name:OMPGitOutput -Value:$Name
            }
        }

        Write-Verbose "$($FunctionName): End."
    }
}



Function Set-OMPProfileSetting {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Set-OMPProfileSetting.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        $Value
    )
    dynamicparam {
        # Create dictionary
        $DynamicParameters = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
        $ValidOMPProfileSettings = ($Script:OMPProfile).keys

        $NewParamSettings = @{
            Name = 'Name'
            Type = 'string'
            ValidateSet = $ValidOMPProfileSettings
            HelpMessage = "The setting to update the value of."
        }

        # Add new dynamic parameter to dictionary
        New-DynamicParameter @NewParamSettings -Dictionary $DynamicParameters

        # Return dictionary with dynamic parameters
        $DynamicParameters
    }
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    process {
        # Pull in the dynamic parameters first
        New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters

        try {
            Write-Verbose "$($FunctionName): Attempting to update the $Name Setting to be $Value."
            Write-Verbose "$($FunctionName): Original value of $($Name) - $($Script:OMPProfile[$Name])"
            $Script:OMPProfile[$Name] = $Value
        }
        catch {
            throw "Unable to update profile setting $Name"
        }
    }
    End {
        try {
            Export-OMPProfile
        }
        catch {
            throw "Unable to update or save the profile!"
        }
    }
}


Function Set-OMPTheme {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Set-OMPTheme.md
    #>

    [CmdletBinding()]
    param (
        [Parameter()]
        [switch]$NoProfileUpdate,
        [Parameter()]
        [switch]$Safe
    )

    dynamicparam {
        # Create dictionary
        $DynamicParameters = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
        $ThemesPath = Join-Path $Script:ModulePath "themes"
        $ValidThemes = @(Get-ChildItem -Path $ThemesPath -File -Filter '*.ps1').BaseName
        $NewParamSettings = @{
            Name = 'Name'
            Position = 0
            Type = 'string'
            ValidateSet = $ValidThemes
            HelpMessage = 'The theme to load. Will be applied immediately'
            ValueFromPipeline = $true
            ValueFromPipelineByPropertyName = $true
        }
        if ($null -ne $Script:OMPProfile['Theme']) {
            $NewParamSettings.ParameterDefaultValue = $Script:OMPProfile['Theme']
        }

        # Add new dynamic parameter to dictionary
        New-DynamicParameter @NewParamSettings -Dictionary $DynamicParameters

        # Return dictionary with dynamic parameters
        $DynamicParameters
    }
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
        $errmsg = $null
    }

    Process {
        if ($PSBoundParameters.ContainsKey('Name')) {
            try {
                if ($null -ne $PSBoundParameters['Name']) {
                    # Pull in the dynamic parameters first
                    New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
                }
            }
            catch {}
        }

        if ([string]::IsNullOrEmpty($Name)) {
            Write-Output 'No theme specified, restoring the original PowerShell prompt and removing current theme'
            Restore-OMPConsolePrompt
            Restore-OMPConsoleTitle
            Restore-OMPConsoleColor
        }
        else {
            $ThemeScriptPath = (Join-Path $Script:ModulePath "themes\$Name.ps1")
            if (Test-Path $ThemeScriptPath) {
                Restore-OMPConsolePrompt
                Restore-OMPConsoleTitle
                Restore-OMPConsoleColor
                Write-Verbose "Loading theme file: $ThemeScriptPath"
                $script = (Get-Content $ThemeScriptPath -Raw)
                try {
                    $sb = [Scriptblock]::create(".{$script}")
                    Invoke-Command -NoNewScope -ScriptBlock $sb -ErrorVariable errmsg 2>$null
                    if (-not ([string]::IsNullOrEmpty($errmsg))) {
                        Write-Verbose "Errors occurred loading $ThemeScriptPath. Errors returned were $errmsg"
                        if ($Safe) {
                            Write-Warning "Errors were found on the error stream when loading the theme and the safe option was set, NOT saving this theme as the theme for this profile."
                            return
                        }
                    }

                    Set-OMPProfileSetting -Name 'Theme' -Value $Name
                }
                catch {
                    Write-Warning "Unable to load theme file $ThemeScriptPath"
                    Write-Warning "Errors reported - $errmsg"
                    throw
                }
            }
            else {
                Throw "Theme with the name $Name was not found (somehow)!"
            }
        }

        if (-not $NoProfileUpdate) {
            $Script:OMPProfile['Theme'] = $Name
            Export-OMPProfile
        }

        Write-Verbose "$($FunctionName): End."
    }
}


Function Set-OMPWindowTitle {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Set-OMPWindowTitle.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Title
    )
    $Global:Host.UI.RawUI.WindowTitle = $Title
}


function Show-OMPHelp {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Show-OMPHelp.md
    #>


    [CmdletBinding()]
    param ()

    $Help = @'
Current OhMyPsh Profile: {{Profile}}
Loaded Plugins: {{Plugins}}
 
OhMyPsh Basics
This module is a personal profile management and profile loading wizard for PowerShell 5.0 (and greater) users that uses a simple
json configuration file to manage plugins, theming, module autoloading, module upgrading, module cleanup, and other chores so
that you can be more productive in the shell.
 
Plugin Power
Plugins are dot sourced files that run scripts or import functions/variables/aliases into your session in a seamless manner. These are extremely powerful and versitile with only a nominal amount of effort to create and deploy. Here are a few examples on what you might do with them:
 
    EXAMPLE 1 - Keep a dumping ground of your personal 'One-off' script functions.
 
    With this module you can quickly load one off functions in your profile every time you start this module. This is common for many users that simply need to use a particular function over and over but don't have a need to turn them into full blown modules.
 
    First create your plugin framwork automatically with:
        New-OMPPlugin -Name 'personalfunctions'
        New-OMPPluginManifest -Name 'personalfunctions' -Description 'My personal functions'
 
    Simply define the function in the global scope like so:
 
        function Global:MyFunction {
            Write-Output 'Test'
        }
 
    Then save the function (or functions) in a file in the plugins\personalfunctions\src directory and run the following:
 
        Add-OMPPlugin -Name 'personalfunctions'
 
    Doing this will automatically update your profile to include the personalfunctions plugin everytime you load OhMyPsh. If this is not what you want then run the following instead to just load it for this session:
 
        Add-OMPPlugin -Name 'personalfunctions' -Force -NoProfileUpdate
 
    EXAMPLE 2 - Run some task every 5th time you load OhMyPsh
 
    Perhaps you need your ego stroked a bit so you you decide to tell yourself how great you are every five times you load OhMyPsh. Easy stuff, first create your template plugin:
 
        New-OMPPlugin -Name 'egoboost'
 
    Next update the returned plugin.ps1 file with the following code:
 
        $Freq = 5
        $TotalRuns = Get-OMPProfileSetting -Name:OMPRunCount
        if (-not ($TotalRuns % $Freq)) {
            Write-Verbose "Total OMP run count is a multiple of the egoboost frequency setting ($Freq)"
            Write-Output "I'm Good Enough, I'm Smart Enough, and Doggone It, People Like Me!"
        }
 
    Test and then add the new plugin to your persistent session:
 
        Add-OMPPlugin -Name 'personalfunctions' -Force -NoProfileUpdate
        Add-OMPPlugin -Name 'personalfunctions' -Force
 
    Unload and reload the module a few times to be given your positive affirmation.
 
NOTE: Exported functions from plugins will not be shown with get-command -module OhMyPsh!
If you want to get a quick view of the functions that are in your session because of plugins then use the following command:
 
    Get-OMPPluginFunction
 
Easy Configuration
A fairly sane default configuration is provided out of the box with this module. You can see all current settings with
the following function:
 
    Get-OMPProfileSetting
 
You can easily modify all of these settings without ever having to open it in an editor. Use the Set-OMPProfileSetting function (which includes tab completion for all settings via the 'Name' Parameter BTW). These settings will instantly save to your persistent profile.
 
    EXAMPLE 1 - Enable verbose output when loading your module
 
        Set-OMPProfileSetting -Name:OMPDebug -Value:$false
 
    EXAMPLE 2 - Disable module auto cleanup (deletion of older version modules)
 
        Set-OMPProfileSetting -Name:AutoCleanOldModules -Value:$false
 
Themes
Themes are simply customized PSColor hash definitions and a prompt that get imported as a ps1 file. Set your theme with Set-OMPTheme.
 
    EXAMPLE 1 - Set the theme to 'norm'
 
        Set-OMPTheme norm
 
Further Information
The entire module is pure powershell and is hosted on github for your convenience. https://www.github.com/zloeber/OhMyPsh
 
'@
 -replace '{{Profile}}', $Script:OMPProfileExportFile -replace '{{Plugins}}', ($Script:OMPState['PluginsLoaded'] -join ', ')

    Write-Output $Help
}


function Show-OMPStatus {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Show-OMPStatus.md
    #>


    [CmdletBinding()]
    param ()

    $Status = @'
Current OhMyPsh Profile: {{Profile}}
Loaded Plugins: {{Plugins}}
'@
 -replace '{{Profile}}', $Script:OMPProfileExportFile -replace '{{Plugins}}', ($Script:OMPState['PluginsLoaded'] -join ', ')

    Write-Output $Status
}


Function Test-OMPConsoleHasANSI {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Test-OMPConsoleHasANSI.md
    #>


    # Powershell ISE don't support ANSI, and this test will print ugly chars
    if($host.PrivateData.ToString() -eq 'Microsoft.PowerShell.Host.ISE.ISEOptions') {
        return $false
    }

    # To test is console supports ANSI, we will print an ANSI code
    # and check if cursor postion has changed. If it has, ANSI is not
    # supported
    $oldPos = $host.UI.RawUI.CursorPosition.X

    Write-Host -NoNewline "$([char](27))[0m" -ForegroundColor ($host.UI.RawUI.BackgroundColor);

    $pos = $host.UI.RawUI.CursorPosition.X

    if($pos -eq $oldPos) {
        return $true
    }
    else {
        # If ANSI is not supported, let's clean up ugly ANSI escapes
        Write-Host -NoNewLine ("`b" * 4)
        return $false
    }
}


function Test-OMPInAGitRepo {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Test-OMPInAGitRepo.md
    #>


    if ((Test-Path ".git") -eq $TRUE) {
        return $TRUE
    }

    # Test within parent dirs
    $checkIn = (Get-Item .).parent
    while ($checkIn -ne $NULL) {
        $pathToTest = $checkIn.fullname + '/.git'
        if ((Test-Path $pathToTest) -eq $TRUE) {
            return $TRUE
        } else {
            $checkIn = $checkIn.parent
        }
    }

    return $FALSE
}



function Test-OMPIsElevated {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Test-OMPIsElevated.md
    #>


    [CmdletBinding()]
    param(
    )
    begin {
        if ($script:ThisModuleLoaded -eq $true) {
            Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
        }
        $FunctionName = $MyInvocation.MyCommand.Name
        Write-Verbose "$($FunctionName): Begin."
    }
    process {
    }
    end {
        switch ( Get-OMPOSPlatform -ErrorVariable null ) {
            'Linux' {
                # Add me!
            }
            'OSX' {
                # Add me!
            }
            Default {
                if (([System.Environment]::OSVersion.Version.Major -gt 5) -and ((New-object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))) {
                    return $true
                }
                else {
                    return $false
                }
            }
        }
        Write-Verbose "$($FunctionName): End."
    }
}



Function Test-OMPProfileSetting {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Test-OMPProfileSetting.md
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [String]$Name
    )
    Process {
        if (($Script:OMPProfile).Keys -contains $Name ) {
            $true
        }
        else {
            $false
        }
    }
}



function Write-OMPGitStatus {
    <#
    .EXTERNALHELP OhMyPsh-help.xml
    .LINK
        https://github.com/zloeber/OhMyPsh/tree/master/release/0.0.7/docs/Functions/Write-OMPGitStatus.md
    #>


    switch ($Script:OMPProfile['OMPGitOutput']) {
        'posh-git' {
            Write-VcsStatus
        }
        'psgit' {
            Write-VcsStatus
        }
        Default {
            # Script or other method
            if (Test-OMPInAGitRepo) {
                $status = Get-OMPGitStatus
                $currentBranch = Get-OMPGitBranchName

                Write-Host '[' -nonewline -foregroundcolor Yellow
                Write-Host $currentBranch -nonewline

                $gitstatus = ' +' + $status["added"] + ' ~' + $status["modified"] + ' -' + $status["deleted"] + ' !' + $status["untracked"] + ']'
                Write-Host $gitstatus -foregroundcolor Yellow -NoNewline
            }
        }
    }
}



## Post-Load Module code ##

# These are core settings which we will not allow to ever get removed
$Script:OMPProfileCoreSettings = @(
    'AutoLoadModules',
    'AutoInstallModules',
    'Plugins',
    'PersonalFunctions',
    'Theme',
    'UnloadModulesOnExit',
    'OMPRunCount',
    'OMPPluginRootPaths',
    'OMPDebug',
    'OMPGitOutput'
)

<#
    Fill out each of the setting hash entries with some sensible defaults.
    This is the master template for user profile settings. Once the module runs once these
    settings are effectively ignored and should be managed via the exported functions instead.
#>

$Script:OMPProfile = @{
    # Load these modules with your OMP profile
    AutoLoadModules = @()
    # Download modules if missing?
    AutoInstallModules = $true
    # Which plugins would you like to load?
    Plugins = @()
    # Personal functions are like plugins but less structured
    PersonalFunctions = @()
    # Theme
    Theme = $null
    # If this is true we will attempt to unload any modules that weren't already loaded when we started
    UnloadModulesOnExit = $true
    # Used to display first time help or just keep a run of how much you love this module
    OMPRunCount = 0
    # Plugins can be located in many locations, this is the list of paths they may reside in
    OMPPluginRootPaths = @((Join-Path $ModulePath "plugins"))
    # Use this to see additional output when loading the module
    OMPDebug = $false
    # Preferred git status method. Used in prompts, specifically in Write-OMPGitStatus. Can be:
    # posh-git (module), psgit (module), script/other (no module, use the crappy baked in scripts with this module instead).
    OMPGitOutput = 'script'
    OMPModuleInstallSplat = @{
        'AllowClobber' = $true
        'Force' = $true
        'Scope' = 'CurrentUser'
    }
}

# Load any persistent data (overrides anything in OMPSettings if the hash element exists)
if ((Test-Path $OMPProfileExportFile)) {
    try {
        Import-OMPProfile -Path $OMPProfileExportFile
    }
    catch {
        throw "Unable to load the OMP profile: $OMPProfileExportFile"
    }
}

$VerbosityFlag = @{}
if ($Script:OMPProfile['OMPDebug']) {
    $VerbosityFlag.Verbose = $true
    $Script:OldVerbosePreference = $VerbosePreference
    $VerbosePreference = "Continue"
}

# We need to keep some state information outside of the profile. This is the hash
# used for this purpose. This combined with Get-OMPState can speed up some operations.
# This is only able to be updated by OMP functions.
$OMPState = @{
    PluginsLoaded = @()
    ModulesAlreadyLoaded = @((Get-Module).Name)
    Platform = Get-OMPOSPlatform
}

<#
    Perform profile processing, this is where all the fun begins...
#>


# 1. Load any specified autoload modules
$Script:OMPProfile['AutoLoadModules'] | Import-OMPModule @VerbosityFlag

# 2. Now the personal functions
$Script:OMPProfile['PersonalFunctions'] | Foreach-Object {
    try {
        Invoke-OMPPersonalFunction -Path $_ -Tag 'personalfunction'
    }
    catch {}
}

# 3. Now the plugins
Write-Verbose 'Loading Plugins:'
Foreach ($Plugin in ($Script:OMPProfile['Plugins'] | Sort-Object)) {
    Write-Verbose "Attempting to load plugin $Plugin"
    try {
        Add-OMPPlugin -Name $Plugin -NoProfileUpdate @VerbosityFlag
        Write-Verbose "Plugin Loaded: $Plugin"
    }
    catch {
        Write-Warning "Unable to load the following plugin: $($_)"
    }
}

# 4. Next the theme
try {
    $Theme = $Script:OMPProfile['Theme']
    if (-not [string]::IsNullOrEmpty($Script:OMPProfile['Theme'])) {
        Set-OMPTheme -Name $Theme -NoProfileUpdate
        Write-Verbose "Theme Loaded: $($Theme)"
    }
}
catch {
    Write-Warning "Unable to load the following theme: $($Theme)"
}

# 5. If we made it this far then we can bump up our run count by 1, save,
# and continue processing items that rely upon this number
$Script:OMPProfile['OMPRunCount'] += 1
Export-OMPProfile -Path $OMPProfileExportFile

########################################################################
# Action to take if the module is removed
$ExecutionContext.SessionState.Module.OnRemove = {
    # Any functions loaded as plugins will get removed from the pssession
    Write-Output "Removing plugin or other dot sourced functions performed within OhMyPsh.."
    Get-ChildItem -Path Function:\ -Recurse | Where-Object { $_.ohmypsh -ne $null } | Remove-Item -Force

    # Run any plugin shutdown code blocks
    Write-Output "Processing OhMyPsh plugin shutdown scriptblocks"
    Invoke-OMPPluginShutdown

    # Remove any newly loaded modules since we started (if enabled)
    if ($Script:OMPProfile['UnloadModulesOnExit']) {
        Write-Output "Removing any modules loaded since OhMyPsh started"
        Get-Module | Where-Object {$OMPState['ModulesAlreadyLoaded'] -notcontains $_.Name} | Foreach-Object {
            if ($_.Name -ne 'OhMyPsh') {
                Write-Output " Module being removed from this session: $($_.Name)"
                Remove-Module -Name $_.Name -Force
            }
        }
    }
    # Restore prompts, tabcompletion, aliases, and console settings
    Restore-OMPConsolePrompt
    Restore-OMPOriginalTabCompletion
    Restore-OMPOriginalPSDefaultParameter
    Restore-OMPOriginalAlias
    Restore-OMPConsoleTitle
    Restore-OMPConsoleColor
}


$null = Register-EngineEvent -SourceIdentifier ( [System.Management.Automation.PsEngineEvent]::Exiting ) -Action {
    # Action to take if the whole pssession is killed
    # Run any plugin shutdown code blocks at the very least.
    Invoke-OMPPluginShutdown
}

if ($Script:OMPProfile['OMPDebug']) {
    $VerbosityFlag = @{}
    $VerbosePreference = $Script:OldVerbosePreference
}

$ThisModuleLoaded = $true