lib/Extensions.ps1

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
function Get-TMExtension {
    <#
    .SYNOPSIS
    Gets/Downloads a Reference Design from the TDS BitBucket tm-reference-designs repo

    .DESCRIPTION
    This function

    .PARAMETER Name
    The name of the Reference Design to download

    .PARAMETER Credential
    The credentials used to log into BitBucket

    .PARAMETER SkipDependencies
    Switch indicating that the Reference Designs on which the named Reference Design
    depends on should not be downloaded

    .PARAMETER ManifestUri
    The uri of the raw rd-manifest.json. Defaults to the file in the __Releases directory

    .PARAMETER Dev
    Switch indicating that all reference designs should be searched/retrieved rather
    than just the published ones

    .PARAMETER ProviderName
    One or more specific Providers to get. All other Providers will be removed from the
    downloaded Reference Design

    .EXAMPLE
    $Credential = Get-StoredCredential -Name 'ME'
    Get-TMExtension -Name 'vmware-vcenter' -Credential $Credential -Dev

    .OUTPUTS
    None
    #>


    [alias('Get-TMReferenceDesign')]
    [CmdletBinding(DefaultParameterSetName = 'Console')]
    param (
        [Parameter(Mandatory = $false, Position = 0, ParameterSetName = 'Console')]
        [String[]]$Name,

        [Parameter(Mandatory = $false, Position = 1)]
        [PSCredential]$Credential,

        [Parameter(Mandatory = $false)]
        [Switch]$SkipDependencies,

        [Parameter(Mandatory = $false)]
        [String]$ManifestUri,

        [Parameter(Mandatory = $false)]
        [Switch]$Dev,

        [Parameter(Mandatory = $false)]
        [String[]]$ProviderName

        # [Parameter(Mandatory = $false, ParameterSetName = "UI")]
        # [Switch]$ShowMenu
        # TODO: Consider if we could add a $Path/$Location type
        # parameter to allow the user to specify a filesystem
    )

    # Some of the TMD functions will be needed in this function
    if (!( Get-Module 'TMD.Common')) {
        Import-Module 'TMD.Common'
    }

    ## Create a $PackageNames variable with all of the Reference Design names (Lower, no spaces)
    $PackageNames = $Name.ToLower() -replace ' - ', '-' -replace ' ', '-'

    ## Save the Progress Preference now so that it can be changed and set back later
    $ProgressPreferenceBackup = $Global:ProgressPreference
    $Global:ProgressPreference = 'SilentlyContinue'

    $ExtensionFolder = Join-Path $Global:userFilesRoot 'Reference Designs'
    $LocalExtensions = [System.Collections.ArrayList]::new()
    $ExtensionsToDownload = [System.Collections.ArrayList]::new()
    # $ShouldInstall = $false

    ## TODO: I don't like this credential handling. If a user supplies a credential, it should not be written to disk, but only used.
    ## To mitigate this, you could do a few things -StoreCredentialAs (Name), or
    ## -CredentialName {Which would hand off to Get-StoredCredential}

    # Check if the credential is already cached
    $CredentialPath = Join-Path -Path $Global:UserPaths.credentials -ChildPath 'Bitbucket.credential'
    if (!$Credential) {
        $Credential = (Test-Path -Path $CredentialPath) ? (Get-StoredCredential -Name 'Bitbucket') : (Get-Credential)
    }

    # Save the credential for future use
    Add-StoredCredential -Name 'Bitbucket' -Credential $Credential
    Write-Verbose 'Credential was stored as Bitbucket.credential'

    # Get the reference design manifest from bitbucket
    Write-Host 'Getting available Reference Designs from Bitbucket...'
    try {
        if ([String]::IsNullOrWhiteSpace($ManifestUri)) {
            $ManifestUri = "https://git.tdsops.com/projects/TM/repos/tm-reference-designs/raw/__Releases/$(if ($Dev) {'dev-'})rd-manifest.json?at=refs%2Fheads%2Fmain"
        }
        $AvailableExtensions = Invoke-RestMethod -Method Get -Uri $ManifestUri -Authentication Basic -Credential $Credential

    } catch {
        throw "Couldn't get the manifest file. Check credentials and try again"
    }
    Write-Host "`tFound " -NoNewline
    Write-Host "$($AvailableExtensions.Count)" -NoNewline -ForegroundColor DarkBlue
    Write-Host ' available Reference Design(s)'

    # Fix the version so that it can be compared later in the script
    for ($i = 0; $i -lt $AvailableExtensions.Count; $i++) {
        $AvailableExtensions[$i].Version = ConvertTo-SemanticVersion -VersionString $AvailableExtensions[$i].Version
        for ($j = 0; $j -lt $AvailableExtensions[$i].extension.dependencies.extensions.Count; $j++) {
            $AvailableExtensions[$i].extension.dependencies.extensions[$j].version = ConvertTo-SemanticVersion -VersionString $AvailableExtensions[$i].extension.dependencies.extensions[$j].version
        }
    }

    # Either show the UI to get the user's selections or
    switch ($PSCmdlet.ParameterSetName) {
        'Console' {
            Write-Verbose 'Console mode was selected'
            # If no name was supplied, just output the Extension objects
            if (!$PackageNames) {
                $AvailableExtensions | ForEach-Object {
                    $_
                }
                return
            } else {
                $PackageNames | ForEach-Object {
                    $Extension = $AvailableExtensions | Where-Object name -EQ $_ |
                        Sort-Object -Property version | Select-Object -Last 1
                        if ($Extension) {
                            [void]$ExtensionsToDownload.Add($Extension)
                        }
                    }
                }
            }
            <#
        "UI" {
            Write-Verbose "UI mode was selected"
            # $ExePath = "..\exe\RD Installer.exe"
            $ExePath = "C:\DEV\git\tm-reference-designs\_ReferenceDesignManager\ReferenceDesignManager\bin\Debug\net5.0-windows\ReferenceDesignManager.exe"
            $StartInfo = [System.Diagnostics.ProcessStartInfo]::new()
            $StartInfo.RedirectStandardError = $true
            $StartInfo.RedirectStandardOutput = $true
            $StartInfo.FileName = $ExePath
            # $StartInfo.ArgumentList = @(
            # "--repocredential `"$CredentialPath`""
            # "--powershell"
            # )
            $StartInfo.Arguments = "--repocredential `"$CredentialPath`" --powershell"

            $ExtensionInstallerProc = [System.Diagnostics.Process]::new()
            $ExtensionInstallerProc.StartInfo = $StartInfo

            # Start the UI and wait for it to exit so that the stdout can be parsed
            Write-Host "Showing UI..."
            $ExtensionInstallerProc.Start()
            $ExtensionInstallerProc.WaitForExit()
            $StdOut = $ExtensionInstallerProc.StandardOutput.ReadToEnd()

            if ([String]::IsNullOrWhiteSpace($StdOut)) {
                throw "Output was not received from $(Split-Path $ExePath -Leaf)"
            }

            $UserChoices = $StdOut | ConvertFrom-Json
            $UserChoices.ExtensionsToDownload | ForEach-Object {
                [void]$ExtensionsToDownload.Add(
                    @{
                        Name = $_
                        Version = $null
                    }
                )
            }
            $ShouldInstall = $UserChoices.ShouldInstall
        }
        #>

        }

        # Make sure one or more available Reference Designs were found
        if ($ExtensionsToDownload.Count -eq 0) {
            throw "No available Reference Designs were found with the specified name(s): $($PackageNames.ToString())"
        }

        ## Create the Destination Downloaded Folder
        $DownloadedFolder = Join-Path $ExtensionFolder 'Downloaded'
        Test-FolderPath $DownloadedFolder

        # Get all of the Reference Designs that are already downloaded
        Write-Host 'Checking for downloaded Reference Designs...'
        Write-Verbose "Looking in '$DownloadFolder'"
        try {
            Get-ChildItem -Path $DownloadedFolder -Filter 'package.json' -Recurse -ErrorAction SilentlyContinue |
                Get-Content -Raw | ConvertFrom-Json | ForEach-Object {
                    [void]$LocalExtensions.Add($_)
                }
    } catch {
        Write-Verbose $_
    }

    Write-Host "`tFound " -NoNewline
    Write-Host "$($LocalExtensions.Count)" -NoNewline -ForegroundColor DarkBlue
    Write-Host ' local Reference Design(s)'

    # Check if the selected Reference Designs have any dependencies on other Reference Designs
    if (!$SkipDependencies) {
        Write-Host 'Checking for Reference Design dependencies...'
        $Count = $ExtensionsToDownload.Count
        for ($i = 0; $i -lt $Count; $i++) {
            $Design = $ExtensionsToDownload[$i]
            foreach ($Dependency in $Design.extension.dependencies.extensions) {
                $AvailableExtension = $AvailableExtensions | Where-Object Name -EQ $Dependency.name |
                    Sort-Object -Property version | Select-Object -Last 1
                if ($AvailableExtension) {
                    $LocalExtension = $LocalExtensions | Where-Object Name -EQ $Dependency.name |
                        Sort-Object -Property version | Select-Object -Last 1
                    if ($LocalExtension) {
                        if ($LocalExtension.version -lt $Dependency.version) {
                            Write-Host "`tFound Reference Design to update: " -NoNewline
                            Write-Host "$($AvailableExtension.Name) - v$($AvailableExtension.Version.ToString())"
                            [void]$ExtensionsToDownload.Add($AvailableExtension)
                        }
                    } else {
                        Write-Host "`tFound additional Reference Design to download: " -NoNewline
                        Write-Host "$($AvailableExtension.Name) - v$($AvailableExtension.Version.ToString())"
                        [void]$ExtensionsToDownload.Add($AvailableExtension)
                    }
                }
            }
        }
    }

    # Start downloading the named reference designs
    Write-Host 'Downloading Reference Designs...'
    # $EncounteredError = $false
    foreach ($ExtensionSpec in $ExtensionsToDownload) {
        Write-Host "`tProcessing: " -NoNewline
        Write-Host $ExtensionSpec.ProductName -ForegroundColor DarkBlue

        ## Resolve the file name and the destination path
        $ZipFileName = $ExtensionSpec.Name + '-' + $ExtensionSpec.Version + '.zip'
        $Url = 'https://git.tdsops.com/projects/TM/repos/tm-reference-designs/raw/__Releases/{0}?at=refs%2Fheads%2Fmain' -f $ZipFileName
        $DestinationFilePath = Join-Path $ExtensionFolder 'Downloaded' $ZipFileName

        try {
            ## Call to Bitbucket to download the file
            Write-Host "`t`tDownloading $ZipFileName ($([Math]::Round(($ExtensionSpec.Size / 1MB), 2)) MB)..." -NoNewline
            Invoke-WebRequest -Uri $Url -Credential $Credential -Authentication Basic -Method Get -OutFile $DestinationFilePath
            Write-Host 'Done' -ForegroundColor Green
        } catch {
            Write-Error $_
            continue
        }

        try {
            # Unzip the downloaded file
            Write-Host "`t`tExpanding archive..." -NoNewline
            $DestinationDirectory = Join-Path $ExtensionFolder 'Downloaded' $ExtensionSpec.ProductName
            Expand-Archive -Path $DestinationFilePath -DestinationPath $DestinationDirectory -Force
            Write-Host 'Done' -ForegroundColor DarkGreen
        } catch {
            Write-Error $_
            continue
        }

        # Remove the .zip file now that its contents been extracted
        Remove-Item -Path $DestinationFilePath -Force

        if ($PSBoundParameters.ContainsKey('ProviderName')) {
            # Remove the actions and Datascripts that don't belong to the specified providers
            $ScriptPaths = @(
                (Join-Path $DestinationDirectory '_REFERENCE DESIGN' 'Actions')
                (Join-Path $DestinationDirectory '_REFERENCE DESIGN' 'ETL')
            )
            Get-ChildItem -Path $ScriptPaths -Directory -Exclude $ProviderName -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force

            # Remove the providers from providers.json that weren't specified in ProviderName
            $FilteredProviders = [System.Collections.ArrayList]::new()
            $ProviderFile = Join-Path $DestinationDirectory '_REFERENCE DESIGN' 'Providers.json'
            $Providers = , @(Get-Content -Path $ProviderFile | ConvertFrom-Json -Depth 10)
            foreach ($Provider in $Providers) {
                if ($Provider.name -in $ProviderName) {
                    [void]($FilteredProviders.Add($Provider))
                }
            }
            ConvertTo-Json -Depth 10 -InputObject $FilteredProviders | Set-Content -Path $ProviderFile -Force
        }
    }

    ## Set the progress preference back
    $Global:ProgressPreference = $ProgressPreferenceBackup

    # if ($ShouldInstall -and !$EncounteredError) {
    # Install-TMExtension -Name $UserChoices.ExtensionsToDownload
    # }
}


function Get-TMLocalExtension {
    <#
    .SYNOPSIS
    Gets one or more Reference Designs that have been downloaded loacally

    .DESCRIPTION
    This function scans the C:\Users\<user>\TMD_Files\Reference Designs directory
    for the package.json file(s) associated with Reference Designs that have been
    downloaded locally

    .PARAMETER Name
    The name(s) of the downloaded Reference Design(s) to retrieve

    .PARAMETER List
    Switch indicating that only a list of downloaded Reference Design names should be returned

    .EXAMPLE
    Get-TMLocalExtension -Name 'vmware-vcenter', 'vmware-hcx'

    .EXAMPLE
    Get-TMLocalExtension -List

    .OUTPUTS
    An array of strings representing the downloaded Reference Design names if the -List switch is used
    otherwise a PSCustomObject for each name that was passed
    #>

    [alias('Get-TMLocalReferenceDesign')]
    [CmdletBinding(DefaultParameterSetName = 'Named')]
    [OutputType([PSCustomObject[]], ParameterSetName = 'Named')]
    [OutputType([String[]], ParameterSetName = 'List')]
    param (
        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'Named',
            ValueFromPipeline = $true)]
        [String[]]$Name,

        [Parameter(Mandatory = $false, ParameterSetName = 'List')]
        [Switch]$List
    )

    begin {
        if (!(Get-Module 'TMD.Common')) {
            Import-Module 'TMD.Common'
        }
        $ExtensionDirectory = Join-Path $Global:userFilesRoot 'Reference Designs'
        $LocalExtensions = Get-ChildItem -Path $ExtensionDirectory -Filter 'package.json' -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {
            $Package = Get-Content -Path $_.FullName -Raw | ConvertFrom-Json -Depth 100
            Add-Member -InputObject $Package -Name 'path' -Value (Split-Path $_.FullName) -MemberType NoteProperty -PassThru -Force
        }
    }

    process {
        if ($List) {
            $LocalExtensions | ForEach-Object {
                $_.Name
            }
        } else {
            if ($Name) {
                $Name | ForEach-Object {
                    $LocalExtensions | Where-Object Name -EQ $_
                }
            } else {
                $LocalExtensions
            }
        }
    }
}


function Import-TMExtension {
    <#
    .SYNOPSIS
    Imports a downloaded Reference Design to the specified project on the specified server

    .DESCRIPTION
    This function will apply the different configuration components of
    a Reference Design into a TransitonManager project.

    .PARAMETER Name
    The name of the locally downloaded Reference Design to apply/install

    .PARAMETER TMSession
    The name of the TM Session to use when creating a Team

    .PARAMETER Project
    The project in which the Reference Design will be applied

    .PARAMETER Exclude
    An array of components to skip when performing the import.
    Options are:
        DependencyTypes
        FieldSpecs
        Bundles
        Providers
        Actions
        Datascripts
        Recipes
        Tags
        AssetViews
        Events
        AppTypes
        DeviceTypes
        Teams
        TaskCategories
        SetupScripts

    .PARAMETER SkipDependencies
    Switch indicating that the Reference Designs on which the named Reference Design
    depends on should not be imported

    .PARAMETER ProviderName
    One or more specific Providers to import. All other Providers will not be
    imported into the project

    .EXAMPLE
    $Credential = Get-StoredCredential -Name 'ME'
    $ImportSplat = @{
        Name = 'vmware-vcenter'
        Project = 'New Project - VMware vCenter'
        TMSession = 'TMAD60'
    }
    Import-TMExtension @ImportSplat

    .OUTPUTS
    None
    #>


    [alias('Import-TMReferenceDesign')]
    [CmdletBinding(DefaultParameterSetName = 'ByInclusion')]
    param (
        [Parameter(
            Mandatory = $true,
            Position = 0,
            ValueFromPipeline = $true)]
        [ArgumentCompleter( { Get-TMLocalExtension -List } )]
        [String[]]$Name,

        [Parameter(Mandatory = $false, Position = 1)]
        [String]$TMSession = 'Default',

        [Parameter(Mandatory = $false, Position = 2)]
        [String]$Project,

        [Parameter(Mandatory = $false, Position = 3, ParameterSetName = 'ByExclusion')]
        [ValidateSet(
            'DependencyTypes',
            'FieldSpecs',
            'Bundles',
            'Providers',
            'Actions',
            'DataScripts',
            'Recipes',
            'Tags',
            'AssetData',
            'AssetViews',
            'Events',
            'AppTypes',
            'DeviceTypes',
            'Teams',
            'TaskCategories',
            'SetupScripts'
        )]
        [String[]]$Exclude,

        [Parameter(Mandatory = $false, Position = 3, ParameterSetName = 'ByInclusion')]
        [ValidateSet(
            '*',
            'DependencyTypes',
            'FieldSpecs',
            'Bundles',
            'Providers',
            'Actions',
            'DataScripts',
            'Recipes',
            'Tags',
            'AssetData',
            'AssetViews',
            'Events',
            'AppTypes',
            'DeviceTypes',
            'Teams',
            'TaskCategories',
            'SetupScripts'
        )]
        [String[]]$Include = '*',

        [Parameter(Mandatory = $false)]
        [Switch]$SkipDependencies,

        [Parameter(Mandatory = $false)]
        [String[]]$ProviderName
    )

    begin {
        # Get the session configuration
        Write-Verbose 'Checking for cached TMSession'
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug 'TMSessionConfig:'
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        if (!(Get-Module 'TMD.Common')) {
            Import-Module 'TMD.Common'
        }

        $FilterByProvider = $PSBoundParameters.ContainsKey('ProviderName')

        ## Tag Color Map
        ## PowerShell Colors:
        ## Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White
        ## TM Tag Colors:
        ## 'Grey', 'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Cyan', 'Purple', 'Pink', 'White'
        $TagColorToForeground = @{
            'Grey'   = 'DarkGray'
            'Red'    = 'Red'
            'Orange' = 'DarkYellow'
            'Yellow' = 'Yellow'
            'Green'  = 'Green'
            'Blue'   = 'Blue'
            'Cyan'   = 'Cyan'
            'Purple' = 'DarkMagenta'
            'Pink'   = 'Magenta'
            'White'  = 'White'
        }

        # Set up a configuration object to determine which components to install later in the process block
        $Components = @{
            DependencyTypes = $true
            FieldSpecs      = $true
            Bundles         = $true
            Providers       = $true
            Actions         = $true
            Datascripts     = $true
            Recipes         = $true
            Tags            = $true
            AssetViews      = $true
            Events          = $true
            AppTypes        = $true
            DeviceTypes     = $true
            Teams           = $true
            TaskCategories  = $true
            SetupScripts    = $true
        }

        switch ($PSCmdlet.ParameterSetName) {
            'ByInclusion' {
                if ($Include -notcontains '*') {
                    foreach ($Key in $Components.GetEnumerator().Name) {
                        if ($Include -notcontains $Key) {
                            $Components.$Key = $false
                        }
                    }
                }
            }

            'ByExclusion' {
                # Process the Exclude parameter and turn components off
                $Exclude | ForEach-Object {
                    $Components.$_ = $false
                }
            }
        }

        # Get a list of all of the Reference Designs that have been saved locally
        $ExtensionDirectory = Join-Path $Global:userFilesRoot 'Reference Designs'
        $LocalExtensions = Get-TMLocalExtension
        if (!$LocalExtensions) {
            throw "No locally saved reference designs were found in $ExtensionDirectory. Use Get-TMExtension to download before installing."
        }

        # Determine the project to export
        if (-not [String]::IsNullOrWhiteSpace($Project) -and ($TMSessionConfig.userContext.project.name -ne $Project)) {
            Enter-TMProject -ProjectName $Project -TMSession $TMSession
        } else {
            $Project = $TMSessionConfig.userContext.project.name
        }
    }

    process {
        # Get the Extension spec from the passed Names and verify they are already downloaded
        $ExtensionToInstall = [System.Collections.Stack]::new()
        $DependencyCheckQueue = [System.Collections.Queue]@()
        foreach ($ExtensionName in $Name) {
            $ExtensionName = $ExtensionName.ToLower().Replace(' - ', '-').Replace(' ', '-')
            $Extension = $LocalExtensions | Where-Object Name -EQ $ExtensionName
            if (!$Extension) {
                throw "The reference design $ExtensionName has not been downloaded locally. Use Get-TMExtension and try again."
            }

            ## Check for Dependencies to add to the list before the Extension being installed
            if (!$SkipDependencies) {

                ## Add This Extension to the DependencyCheckList
                $DependencyCheckQueue.Enqueue($Extension)
            }

            ## Add the Extension being installed to the list, after dependencies are added
            $ExtensionToInstall.Push($Extension)
        }

        ## Check every Reference Design for Dependencies
        if (-Not $SkipDependencies) {

            Write-Host 'Checking Dependency Requirements'
            while ($DependencyCheckQueue.Count -ne 0) {

                # ## Check Each of the Extensions that are queued for installation for Dependencies
                # foreach ($ExtensionCheck in $ExtensionsToCheckDependenciesFor) {
                $ExtensionCheck = $DependencyCheckQueue.Dequeue()

                ## Remove Placeholder tokens provided by the template file creation
                $DependentExtensions = @()
                $ExtensionCheck.referenceDesign.dependencies.referenceDesigns | Where-Object { $_.name -ne '<PLACEHOLDER>' } | ForEach-Object {
                    if ($_) { $DependentExtensions += $_ }
                }
                $ExtensionCheck.extension.dependencies.extensions | Where-Object { $_.name -ne '<PLACEHOLDER>' } | ForEach-Object {
                    if ($_) { $DependentExtensions += $_ }
                }

                foreach ($DependencyItem in $DependentExtensions) {

                    ## Get the Highest version number that matches the requirement
                    $Dependency = $LocalExtensions
                    | Where-Object { $_.Name -eq $DependencyItem.Name -and $_.Version -ge $DependencyItem.Version }
                    | Sort-Object -Property 'version' -Descending
                    | Select-Object -First 1

                    ## Ensure a dependency was found
                    if (!$Dependency) {
                        throw "The dependency Reference Design $($DependencyItem.Name) (Minimum v$($DependencyItem.Version)) was not found on the local hard drive. Use Get-TMExtension and try again."
                    }

                    if ($ExtensionToInstall -notcontains $Dependency) {
                        Write-Host 'Required Prerequisite Extension also will be installed: ' -NoNewline
                        Write-Host $Dependency.name -ForegroundColor Cyan -NoNewline
                        Write-Host " v$($Dependency.version)" -ForegroundColor DarkGray
                        # $ExtensionToInstall += $Dependency
                        $ExtensionToInstall.Push($Dependency)
                        [void]($DependencyCheckQueue.Enqueue($Dependency))
                    }
                }
            }
        }
        ## Create an array of Setup Scripts to run
        $SetupScriptsToRun = [System.Collections.ArrayList]@()

        ## Iterate over each Reference Design to Install
        while ($ExtensionToInstall.Count) {

            ## Get the next item from the Stack
            $Extension = $ExtensionToInstall.Pop()

            Write-Host 'Importing: ' -NoNewline
            Write-Host $Extension.productName -NoNewline -ForegroundColor Cyan
            Write-Host ', Version: ' -NoNewline
            Write-Host $Extension.Version -ForegroundColor DarkGray

            $ExtensionPath = Join-Path $Extension.Path '_REFERENCE DESIGN'

            # Create the dependency types
            if ($Components.DependencyTypes) {
                Write-Host 'Loading Dependency Types...'
                $DependencyTypes = [system.collections.arraylist]@()
                $DependencyTypesFolderPath = Join-Path $ExtensionPath 'DependencyTypes'
                if (Test-Path $DependencyTypesFolderPath -ErrorAction SilentlyContinue) {
                    $DependencyTypeFiles = Get-ChildItem -Path $DependencyTypesFolderPath -ErrorAction SilentlyContinue
                    $DependencyTypeFiles | ForEach-Object {
                        [void]($DependencyTypes.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }

                } else {
                    $DependencyTypesFilePath = Join-Path $ExtensionPath 'DependencyTypes.json'
                    if (Test-Path $DependencyTypesFilePath -ErrorAction SilentlyContinue) {
                        $DependencyTypes = Get-ChildItem -Path $DependencyTypesFilePath -ErrorAction SilentlyContinue | Get-Content | ConvertFrom-Json
                    }
                }

                ## Check if there were any entries
                if ($DependencyTypes.Count -eq 0) {
                    Write-Host "`tNo Dependency Types to add"
                } else {

                    ## Get the Server's existing Dependency Types
                    $ServerDependencyTypes = Get-TMDependencyType -TMSession $TMSession
                    foreach ($DependencyType in $DependencyTypes) {

                        ## If the server doesn't have the dependency type
                        if ($ServerDependencyTypes.label -notcontains $DependencyType.label) {

                            ## Add it to the server
                            Write-Host "`tLoading Dependency Type: " -NoNewline
                            Write-Host "$($DependencyType.label)" -ForegroundColor DarkBlue
                            $DependencyType = [TMDependencyType]::new($DependencyType.label)
                            New-TMDependencyType -TMSession $TMSession -DependencyType $DependencyType
                        }
                    }
                }
            }

            # Create the App types
            if ($Components.AppTypes) {
                Write-Host 'Loading App Types...'
                $AppTypes = [system.collections.arraylist]@()
                $AppTypesFolderPath = Join-Path $ExtensionPath 'AppTypes'
                if (Test-Path $AppTypesFolderPath -ErrorAction SilentlyContinue) {
                    $AppTypeFiles = Get-ChildItem -Path $AppTypesFolderPath -ErrorAction SilentlyContinue
                    $AppTypeFiles | ForEach-Object {
                        [void]($AppTypes.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }
                } else {
                    $AppTypesFilePath = Join-Path $ExtensionPath 'AppTypes.json'
                    if (Test-Path $AppTypesFilePath -ErrorAction SilentlyContinue) {
                        $AppTypes = Get-Content -Path $AppTypesFilePath | ConvertFrom-Json
                    }
                }

                ## Check if there were any entries
                if ($AppTypes.Count -eq 0) {
                    Write-Host "`tNo App Types to add"
                } else {

                    ## Get the Server's existing App Types
                    $ServerAppTypes = Get-TMAssetOption -Type 'App Type' -TMSession $TMSession
                    foreach ($AppType in $AppTypes) {

                        ## If the server doesn't have the App type
                        if ($ServerAppTypes.label -notcontains $AppType.label) {

                            ## Add it to the server
                            Write-Host "`tLoading App Type: " -NoNewline
                            Write-Host "$($AppType.label)" -ForegroundColor DarkBlue
                            $AppType = [TMAppType]::new($AppType.label)
                            New-TMAssetOption -Type 'App Type' -Name $AppType.label -TMSession $TMSession
                        }
                    }
                }
            }

            # Create the Device types
            if ($Components.DeviceTypes) {
                Write-Host 'Loading Device Types...'
                $DeviceTypes = [system.collections.arraylist]@()
                $DeviceTypesFolderPath = Join-Path $ExtensionPath 'DeviceTypes'
                if (Test-Path $DeviceTypesFolderPath -ErrorAction SilentlyContinue) {
                    $DeviceTypeFiles = Get-ChildItem -Path $DeviceTypesFolderPath -ErrorAction SilentlyContinue
                    $DeviceTypeFiles | ForEach-Object {
                        [void]($DeviceTypes.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }
                } else {

                    $DeviceTypesFilePath = Join-Path $ExtensionPath 'DeviceTypes.json'
                    if (Test-Path $AppTypesFilePath -ErrorAction SilentlyContinue) {
                        $DeviceTypes = Get-Content -Path $DeviceTypesFilePath | ConvertFrom-Json
                    }
                }

                if ($DeviceTypes.Count -eq 0) {
                    Write-Host "`tNo Device Types to add"
                } else {

                    ## Get the Server's existing Device Types
                    $ServerDeviceTypes = Get-TMAssetOption -Type 'Asset Type' -TMSession $TMSession
                    foreach ($DeviceType in $DeviceTypes) {

                        ## If the server doesn't have the Device type
                        if ($ServerDeviceTypes.label -notcontains $DeviceType.label) {

                            ## Add it to the server
                            Write-Host "`tLoading Device Type: " -NoNewline
                            Write-Host "$($DeviceType.label)" -ForegroundColor DarkBlue
                            $DeviceType = [TMAssetType]::new($DeviceType.label)
                            New-TMAssetOption -Type 'Asset Type' -Name $DeviceType.label -TMSession $TMSession
                        }
                    }
                }
            }

            # Create the Task Categories
            if ($Components.TaskCategories) {
                Write-Host 'Loading Task Categories...'
                $TaskCategories = [system.collections.arraylist]@()
                $TaskCategoriesFolderPath = Join-Path $ExtensionPath 'TaskCategories'
                if (Test-Path $TaskCategoriesFolderPath -ErrorAction SilentlyContinue) {
                    $TaskCategoryFiles = Get-ChildItem -Path $TaskCategoriesFolderPath -ErrorAction SilentlyContinue
                    $TaskCategoryFiles | ForEach-Object {
                        [void]($TaskCategories.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }
                } else {
                    $TaskCategoriesFilePath = Join-Path $ExtensionPath 'TaskCategories.json'
                    if (Test-Path $TaskCategoriesFilePath -ErrorAction SilentlyContinue) {
                        $TaskCategories = Get-Content -Path $TaskCategoriesFilePath | ConvertFrom-Json
                    }
                }

                if ($TaskCategories.Count -eq 0) {
                    Write-Host "`tNo Task Categroies to add"
                } else {

                    ## Get the Server's existing Task Categories
                    $ServerTaskCategories = Get-TMAssetOption -Type 'Task Category' -TMSession $TMSession
                    foreach ($TaskCategory in $TaskCategories) {

                        ## If the server doesn't have the Device type
                        if ($ServerTaskCategories.label -notcontains $TaskCategory.label) {

                            ## Add it to the server
                            Write-Host "`tLoading Task Category: " -NoNewline
                            Write-Host "$($TaskCategory.label)" -ForegroundColor DarkBlue
                            $TaskCategory = [TMTaskCategory]::new($TaskCategory.label)
                            New-TMAssetOption -Type 'Task Category' -Name $TaskCategory.label -TMSession $TMSession
                        }
                    }
                }
            }

            # Load the Teams
            if ($Components.Teams) {
                Write-Host 'Loading Teams...'
                $Teams = [system.collections.arraylist]@()
                $TeamsFolderPath = Join-Path $ExtensionPath 'Teams'
                if (Test-Path $TeamsFolderPath -ErrorAction SilentlyContinue) {
                    $TeamFiles = Get-ChildItem -Path $TeamsFolderPath -ErrorAction SilentlyContinue
                    $TeamFiles | ForEach-Object {
                        [void]($Teams.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }
                } else {
                    $TeamsFilePath = Join-Path $ExtensionPath 'Teams.json'
                    if (Test-Path $TeamsFilePath -ErrorAction SilentlyContinue) {
                        $Teams = Get-Content -Path $TeamsFilePath | ConvertFrom-Json
                    }
                }

                if ($Teams.Count -eq 0) {
                    Write-Host "`tNo Teams to add"
                } else {
                    foreach ($Team in $Teams) {
                        Write-Host "`tLoading Team: " -NoNewline
                        Write-Host "$($Team.Code)" -ForegroundColor DarkBlue
                        New-TMTeam -Code $Team.Code -Description $Team.Description -Level $Team.Level -Help $Team.Help -TMSession $TMSession
                    }
                }
            }

            # Load the Tags
            if ($Components.Tags) {
                Write-Host 'Loading Tags...'
                $Tags = [system.collections.arraylist]@()
                $TagsFolderPath = Join-Path $ExtensionPath 'Tags'
                if (Test-Path $TagsFolderPath -ErrorAction SilentlyContinue) {
                    $TagFiles = Get-ChildItem -Path $TagsFolderPath -ErrorAction SilentlyContinue
                    $TagFiles | ForEach-Object {
                        [void]($Tags.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }
                } else {
                    $TagsFilePath = Join-Path $ExtensionPath 'Tags.json'
                    if (Test-Path $TagsFilePath -ErrorAction SilentlyContinue) {
                        $Tags = Get-Content -Path $TagsFilePath | ConvertFrom-Json
                    }
                }
                if ($Tags.Count -eq 0) {
                    Write-Host "`tNo Tags to add"
                } else {
                    foreach ($Tag in $Tags) {
                        Write-Host "`tLoading Tag: " -NoNewline
                        Write-Host "$($Tag.Name)" -ForegroundColor $TagColorToForeground.($Tag.Color)
                        New-TMTag -Name $Tag.Name -Description $Tag.description -Color $Tag.color -TMSession $TMSession
                    }
                }
            }

            # Load the Field Specs
            if ($Components.FieldSpecs) {
                Write-Host 'Loading Field Specs...'

                ## Check Extension Package v3 (Folder of Files)
                $FieldSpecsFolderPath = Join-Path $ExtensionPath 'FieldSpecs'
                if(Test-Path $FieldSpecsFolderPath -ErrorAction SilentlyContinue){

                    ## Create the FieldSpecs Object to add all of the fields to
                    $FieldSpecs = [pscustomobject]@{
                        APPLICATION = [PSCustomObject]@{
                            lastUpdated = ''
                            dateCreated = ''
                            domain = 'APPLICATION'
                            fields = @()
                            version = 1
                        }
                        DATABASE = [PSCustomObject]@{
                            lastUpdated = ''
                            dateCreated = ''
                            domain = 'DATABASE'
                            fields = @()
                            version = 1
                        }
                        DEVICE = [PSCustomObject]@{
                            lastUpdated = ''
                            dateCreated = ''
                            domain = 'DEVICE'
                            fields = @()
                            version = 1
                        }
                        STORAGE = [PSCustomObject]@{
                            lastUpdated = ''
                            dateCreated = ''
                            domain = 'STORAGE'
                            fields = @()
                            version = 1
                        }
                    }

                    ## Handle Single JSON field files from folders
                    $SharedFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Shared') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
                    foreach ($FieldFile in $SharedFieldFiles) {
                        $FieldSpecs.APPLICATION.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
                        $FieldSpecs.DATABASE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
                        $FieldSpecs.DEVICE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
                        $FieldSpecs.STORAGE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
                    }

                    $ApplicationFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Application') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
                    foreach ($FieldFile in $ApplicationFieldFiles) {
                        $FieldSpecs.APPLICATION.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
                    }

                    $DatabaseFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Database') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
                    foreach ($FieldFile in $DatabaseFieldFiles) {
                        $FieldSpecs.DATABASE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
                    }

                    $DeviceFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Device') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
                    foreach ($FieldFile in $DeviceFieldFiles) {
                        $FieldSpecs.DEVICE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
                    }

                    $StorageFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Storage') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
                    foreach ($FieldFile in $StorageFieldFiles) {
                        $FieldSpecs.STORAGE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
                    }

                }else {

                    ## Check Extension Package <v3 (Single FieldSpecs.json file)
                    $FieldSpecsFilePath = Join-Path $ExtensionPath 'FieldSpecs.json'
                    if (Test-Path $FieldSpecsFilePath -ErrorAction SilentlyContinue) {

                        $TMVersion = [Version]::parse($TMSessionConfig.TMVersion)

                        ## Version 6.0.2.1+ (and TODO version 6.1?, 5x?)
                        ## Requires the class names to be lower case
                        if ($TMVersion.Major -eq 6 -and $TMVersion -ge '6.1.0') {
                            ## Convert each Asset Class name to lowercase
                            $FieldSpecs = ((Get-Content -Path $FieldSpecsFilePath) -replace 'constraints', 'constraint')
                        } else {
                            ## No conversion is necessary, assign the provided fields as the updates
                            $FieldSpecs = (((Get-Content -Path $FieldSpecsFilePath) -replace 'constraint', 'constraints') -replace 'constraintss', 'constraints')
                        }
                    }
                    $FieldSpecs = $FieldSpecs | ConvertFrom-Json
                }

                ## Determine if any fields are needed
                if(-Not $FieldSpecs){
                    Write-Host "`tNo Asset Field Specs to add"
                } else {
                    'APPLICATION', 'DEVICE', 'DATABASE', 'STORAGE' | ForEach-Object {
                        $DomainColor = switch ($_) {
                            'APPLICATION' { 'DarkMagenta' }
                            'DEVICE' { 'DarkCyan' }
                            'DATABASE' { 'DarkYellow' }
                            'STORAGE' { 'DarkGreen' }
                        }
                        foreach ($Field in $FieldSpecs.$_.fields) {
                            Write-Host "`tLoading Field Spec: [" -NoNewline
                            Write-Host "$_" -ForegroundColor $DomainColor -NoNewline
                            Write-Host '] ' -NoNewline
                            Write-Host "$($Field.label)" -ForegroundColor DarkBlue
                        }
                    }
                    Update-TMFieldSpecs -FieldSpecs $FieldSpecs -TMSession $TMSession
                }
            }

            # Load the Bundles
            if ($Components.Bundles) {
                Write-Host 'Loading Bundles...'
                $Bundles = [system.collections.arraylist]@()
                $BundlesFolderPath = Join-Path $ExtensionPath 'Bundles'
                if (Test-Path $BundlesFolderPath -ErrorAction SilentlyContinue) {
                    $BundleFiles = Get-ChildItem -Path $BundlesFolderPath -ErrorAction SilentlyContinue
                    $BundleFiles | ForEach-Object {
                        [void]($Bundles.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }
                } else {
                    $BundlesFilePath = Join-Path $ExtensionPath 'Bundles.json'
                    if (Test-Path $BundlesFilePath -ErrorAction SilentlyContinue) {
                        $Bundles = Get-Content -Path $BundlesFilePath | ConvertFrom-Json
                    }
                }
                if ($Bundles.Count -eq 0) {
                    Write-Host "`tNo Bundles to add"
                } else {
                    foreach ($Bundle in $Bundles) {
                        Write-Host "`tLoading Bundle: " -NoNewline
                        Write-Host "$($Bundle.Name)" -ForegroundColor DarkBlue
                        New-TMBundle -Bundle $Bundle -TMSession $TMSession
                    }
                }
            }

            # Load the Events
            if ($Components.Events) {
                Write-Host 'Loading Events...'
                $Events = [system.collections.arraylist]@()
                $EventsFolderPath = Join-Path $ExtensionPath 'Events'
                if (Test-Path $EventsFolderPath -ErrorAction SilentlyContinue) {
                    $EventFiles = Get-ChildItem -Path $EventsFolderPath -ErrorAction SilentlyContinue
                    $EventFiles | ForEach-Object {
                        [void]($Events.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }
                } else {
                    $EventsFilePath = Join-Path $ExtensionPath 'Events.json'
                    if (Test-Path $EventsFilePath -ErrorAction SilentlyContinue) {
                        $Events = Get-Content -Path $EventsFilePath | ConvertFrom-Json
                    }
                }
                if ($Events.Count -eq 0) {
                    Write-Host "`tNo Events to add"
                } else {
                    foreach ($TMEvent in $Events) {
                        Write-Host "`tLoading Event: " -NoNewline
                        Write-Host "$($TMEvent.Name)" -ForegroundColor DarkBlue
                        New-TMEvent $TMEvent -TMSession $TMSession
                    }
                }
            }

            # Load the Providers
            if ($Components.Providers) {
                Write-Host 'Loading Providers...'
                $Providers = [system.collections.arraylist]@()
                $ProvidersFolderPath = Join-Path $ExtensionPath 'Providers'
                if (Test-Path $ProvidersFolderPath -ErrorAction SilentlyContinue) {
                    $ProviderFiles = Get-ChildItem -Path $ProvidersFolderPath -ErrorAction SilentlyContinue
                    $ProviderFiles | ForEach-Object {
                        [void]($Providers.Add((Get-Content -Path $_.FullName | ConvertFrom-Json)))
                    }
                } else {
                    $ProvidersFilePath = Join-Path $ExtensionPath 'Providers.json'
                    if (Test-Path $ProvidersFilePath -ErrorAction SilentlyContinue) {
                        $Providers = Get-Content -Path $ProvidersFilePath | ConvertFrom-Json
                    }
                }
                if ($Providers.Count -eq 0) {
                    Write-Host "`tNo Providers to add"
                } else {
                    foreach ($Provider in $Providers) {
                        if ($FilterByProvider -and ($Provider.Name -notin $ProviderName)) {
                            continue
                        }
                        Write-Host "`tLoading Provider: " -NoNewline
                        Write-Host "$($Provider.Name)" -ForegroundColor DarkBlue
                        New-TMProvider -Provider $Provider -TMSession $TMSession
                    }
                }
            }

            # Load Actions
            if ($Components.Actions) {
                Write-Host 'Loading Actions...'
                $Actions = @()
                $ActionsPath = Join-Path $ExtensionPath 'Actions'
                if (Test-Path -Path $ActionsPath -ErrorAction SilentlyContinue) {
                    $Actions = Get-ChildItem -Path $ActionsPath -Recurse -Include '*.ps1' -ErrorAction SilentlyContinue | ForEach-Object {
                        Read-TMActionScriptFile -Path $_.FullName
                    }
                }

                if ($FilterByProvider) {
                    $Actions = $Actions | Where-Object { $_.Provider.Name -in $ProviderName }
                }

                if ($Actions.count -eq 0) {
                    Write-Host "`tNo Actions to add"
                } else {
                    foreach ($Action in $Actions) {
                        Write-Host "`tLoading Action: " -NoNewline
                        Write-Host "$($Action.Name)" -ForegroundColor DarkBlue
                        New-TMAction -Action $Action -Update -TMSession $TMSession
                    }
                }
            }

            # DataScripts
            if ($Components.Datascripts) {
                Write-Host 'Loading DataScripts...'
                $DataScripts = @()
                $DataScriptsPath = Join-Path $ExtensionPath 'DataScripts'
                if (Test-Path -Path $DataScriptsPath -ErrorAction SilentlyContinue) {
                    $DataScripts = Get-ChildItem -Path $DataScriptsPath -Recurse -Include '*.groovy' -ErrorAction SilentlyContinue | ForEach-Object {
                        Read-TMDatascriptFile -Path $_.FullName
                    }
                }

                if ($FilterByProvider) {
                    $DataScripts = $DataScripts | Where-Object { $_.Provider.Name -in $ProviderName }
                }

                if ($DataScripts.count -eq 0) {
                    Write-Host "`tNo DataScripts to add"
                } else {
                    foreach ($DataScript in $DataScripts) {
                        Write-Host "`tLoading DataScript: " -NoNewline
                        Write-Host "$($DataScript.Name)" -ForegroundColor DarkBlue
                        New-TMDatascript -Datascript $DataScript -Update -TMSession $TMSession
                    }
                }
            }

            # Recipes
            if ($Components.Recipes) {
                Write-Host 'Loading Recipes...'
                $Recipes = @()
                $RecipesPath = Join-Path $ExtensionPath 'Recipes'
                if (Test-Path -Path $RecipesPath -ErrorAction SilentlyContinue) {
                    $Recipes = Get-ChildItem -Path $RecipesPath -Recurse -Include '*.json' -ErrorAction SilentlyContinue | ForEach-Object {
                        Read-TMRecipeScriptFile -Path $_.FullName -UpdateFieldNames
                    }
                }

                if ($Recipes.count -eq 0) {
                    Write-Host "`tNo DataScripts to add"
                } else {
                    foreach ($Recipe in $Recipes) {
                        Write-Host "`tLoading Recipe: " -NoNewline
                        Write-Host "$($Recipe.Name)" -ForegroundColor DarkBlue
                        New-TMRecipe -Recipe $Recipe -Update -TMSession $TMSession
                    }
                }
            }

            # Load the AssetViews
            if ($Components.AssetViews) {

                ## Convert any Custom Field Label Tokens from a template
                ## Get a FieldToLabel map to build string replacements
                $AssetViews = [System.Collections.ArrayList]@()
                $LabelReplacements = [System.Collections.ArrayList]@()
                $FieldToLabelMap = Get-TMFieldToLabelMap

                ## Create a replacement token for each asset/label = field set
                foreach ($DomainClass in @('DEVICE', 'APPLICATION', 'DATABASE', 'STORAGE' )) {

                    foreach ($FieldName in $FieldToLabelMap.$DomainClass.Keys) {
                        if ($FieldName -match 'custom\d+') {

                            # Write-Host $FieldName
                            [void]($LabelReplacements.Add([pscustomobject]@{
                                        DomainClass = $DomainClass
                                        FieldLabel  = $FieldToLabelMap.$DomainClass.$FieldName
                                        FieldName   = $FieldName
                                    }
                                )
                            )
                        }
                    }
                }

                $AssetViewsFolderPath = Join-Path $ExtensionPath 'AssetViews'
                $AssetViewsFilePath = Join-Path $ExtensionPath 'AssetViews.json'

                Write-Host 'Loading AssetViews...'
                if (Test-Path $AssetViewsFolderPath -ErrorAction SilentlyContinue) {
                    $AssetViews = Get-ChildItem -Path $AssetViewsFolderPath -File -ErrorAction SilentlyContinue |
                        Where-Object { $_.Extension -in @('.json') } |
                        ForEach-Object {
                            Get-Content -Path $_.FullName | ConvertFrom-Json
                        }
                } else {
                    if (-Not (Test-Path $AssetViewsFilePath -ErrorAction SilentlyContinue)) {
                        Write-Host "`tNo AssetViews to add"
                    } else {
                        $AssetViews = Get-Content -Path $AssetViewsFilePath | ConvertFrom-Json
                        if ($AssetViews.Count -eq 0) { Write-Host "`tNo Asset Views to add" }
                    }
                }
                foreach ($AssetView in $AssetViews) {
                    Write-Host "`tLoading AssetView: " -NoNewline
                    Write-Host "$($AssetView.Name)" -ForegroundColor DarkBlue

                    ## Replace all 'customN' items with a codestring to replace the correct items in the offline package
                    $SourceCodeLines = ($AssetView | ConvertTo-Json -Depth 100) -split "`r`n" -split "`r" -split "`n"
                    $UpdatedSourceCodeLines = [System.Collections.ArrayList]::new()

                    foreach ($SourceCodeLine in $SourceCodeLines) {
                        $CurrentLine = $SourceCodeLine
                        $LabelReplacements | ForEach-Object {
                            $ReplaceString = "customN\|$($_.DomainClass)\|$($_.FieldLabel)\|"
                            if ($CurrentLine -match $ReplaceString) {
                                $CurrentLine = $CurrentLine -replace $ReplaceString, $_.FieldName
                            }
                        }
                        [void]($UpdatedSourceCodeLines.Add($CurrentLine))
                    }
                    $AssetView = $UpdatedSourceCodeLines -Join "`n" | ConvertFrom-Json

                    New-TMAssetViewConfiguration $AssetView -TMSession $TMSession -Update
                }
            }

            # SetupScripts
            if ($Components.SetupScripts) {
                Write-Host 'Collecting Setup Scripts...'
                $SetupScriptsFolderPath = Join-Path $ExtensionPath '_SETUP'
                if (-Not (Test-Path $SetupScriptsFolderPath -ErrorAction SilentlyContinue)) {
                    Write-Host "`tNo Setup Scripts to run"
                } else {
                    $SetupScriptFiles = Get-ChildItem -Path $SetupScriptsFolderPath -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -eq '.ps1' }
                    foreach ($SetupScriptFile in $SetupScriptFiles) {
                        Write-Host "`Queuing Setup Script: " -NoNewline
                        Write-Host "$($SetupScriptFile.Name)" -ForegroundColor DarkBlue
                        [void]$SetupScriptsToRun.Add($SetupScriptFile)
                    }
                }
            }
        }

        ## Sort the Setup Scripts to run by name
        $SortedSetupScripts = $SetupScriptsToRun | Sort-Object -Property 'Name'

        ## Iterate over each setup script and run them each
        foreach ($SetupScript in $SortedSetupScripts) {

            Write-Host "`tRunning Setup Script: " -NoNewline
            Write-Host "$($SetupScript.Name)" -ForegroundColor DarkBlue

            ## Try the script
            try {

                & "$($SetupScript.FullName)"
            } catch {
                Write-Host 'Setup Script Failed!'
                Write-Error $_
            }
        }
    }
}

function Export-TMExtension {
    <#
    .SYNOPSIS
    Exports a TransitionManager project into a portable configuration package
    that can be applied in a different project and/or on a different server

    .DESCRIPTION
    This function will retreieve the different configuration components from a
    TransitonManager project and save them locally in a standardized format
    that can then be used to import those configurations on another TM project
    or TM instance.

    .PARAMETER Name
    What the Reference Design will be named

    .PARAMETER TMSession
    The name of the TM Session to use when creating a Team

    .PARAMETER Project
    The project that will be exported

    .PARAMETER Exclude
    An array of components to skip when performing the export.
    Options are:
        DependencyTypes
        FieldSpecs
        Bundles
        Providers
        Actions
        DataScripts
        Recipes
        AssetViews
        Events
        AppTypes
        DeviceTypes
        Teams
        TaskCategories

    .PARAMETER OutPath
    The directory where the Reference Design will be saved

    .EXAMPLE
    $Credential = Get-StoredCredential -Name 'ME'
    $ExportSplat = @{
        Name = 'VMWare - vCenter'
        Server = 'tmddev.transitionmanager.net'
        Project = 'Extension - VMware vCenter'
        Credential = $Credential
    }
    Export-TMExtension @ExportSplat

    .OUTPUTS
    None
    #>


    [alias('Export-TMExtension')]
    [CmdletBinding(DefaultParameterSetName = 'ByInclusion')]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$Name,

        [Parameter(Mandatory = $false, Position = 1)]
        [String]$TMSession = 'Default',

        [Parameter(Mandatory = $false, Position = 2)]
        [String]$Project,

        [Parameter(Mandatory = $false, Position = 3, ParameterSetName = 'ByInclusion')]
        [ValidateSet(
            '*',
            'DependencyTypes',
            'FieldSpecs',
            'Bundles',
            'Providers',
            'Actions',
            'DataScripts',
            'Recipes',
            'Tags',
            'AssetData',
            'AssetViews',
            'Events',
            'AppTypes',
            'DeviceTypes',
            'Teams',
            'TaskCategories'
        )]
        [String[]]$Include = '*',

        [Parameter(Mandatory = $false, Position = 3, ParameterSetName = 'ByExclusion')]
        [ValidateSet(
            'DependencyTypes',
            'FieldSpecs',
            'Bundles',
            'Providers',
            'Actions',
            'DataScripts',
            'Recipes',
            'Tags',
            'AssetData',
            'AssetViews',
            'Events',
            'AppTypes',
            'DeviceTypes',
            'Teams',
            'TaskCategories'
        )]
        [String[]]$Exclude,

        [Parameter(Mandatory = $false, Position = 4)]
        [String[]]$ProviderName,

        [Parameter(Mandatory = $false, Position = 5)]
        [AllowNull()]
        [String]$OutPath = '',

        [Parameter(Mandatory = $false, Position = 6)]
        [Switch]$ClearExistingFiles
    )

    begin {

        # Get the session configuration
        Write-Verbose 'Checking for cached TMSession'
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug 'TMSessionConfig:'
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        if (!(Get-Module 'TMD.Common')) {
            Import-Module 'TMD.Common'
        }

        # Default to the reference design directory if an out path wasn't specified
        if ([String]::IsNullOrWhiteSpace($OutPath)) {
            Write-Verbose 'No OutPath as provided and will use the default export location'
            $OutPath = Join-Path $Global:userPaths.referencedesigns 'Exported' $TMSessionConfig.TMServer
        }

        # Set up a configuration object to determine which components to install later in the process block
        $Components = @{
            DependencyTypes = $true
            FieldSpecs      = $true
            Bundles         = $true
            Providers       = $true
            Actions         = $true
            DataScripts     = $true
            Recipes         = $true
            Tags            = $true
            AssetData       = $true
            AssetViews      = $true
            Events          = $true
            AppTypes        = $true
            DeviceTypes     = $true
            Teams           = $true
            TaskCategories  = $true
        }

        switch ($PSCmdlet.ParameterSetName) {
            'ByInclusion' {
                if ($Include -notcontains '*') {
                    foreach ($Key in $Components.GetEnumerator().Name) {
                        if ($Include -notcontains $Key) {
                            $Components.$Key = $false
                        }
                    }
                }
            }

            'ByExclusion' {
                # Process the Exclude parameter and turn components off
                $Exclude | ForEach-Object {
                    $Components.$_ = $false
                }
            }
        }

        # Write about what is going to be exported
        Write-Host 'Exporting Component Types from Project:'
        foreach ($Component in $Components.Keys) {

            ## For each Enabled Component
            if ($Components.$Component) {
                Write-Host "`t$Component" -ForegroundColor Cyan
            }
        }

        # Determine the project to export
        if (-not [String]::IsNullOrWhiteSpace($Project) -and ($TMSessionConfig.userContext.project.name -ne $Project)) {
            Enter-TMProject -ProjectName $Project -TMSession $TMSession
        } else {
            $Project = $TMSessionConfig.userContext.project.name
        }

        ## Set the name to the project name if it wasn't provided
        $Name = [String]::IsNullOrWhiteSpace($Name) ? $Project : $Name

        ## Write a Banner
        Write-Host 'Exporting TM Extension From:'
        Write-Host "`tServer: " -NoNewline
        Write-Host $TMSessionConfig.TMServer -ForegroundColor Cyan
        Write-Host "`tProject: " -NoNewline
        Write-Host $Project -ForegroundColor Cyan
        Write-Host "`tAt: " -NoNewline
        Write-Host (Get-Date).ToString() -ForegroundColor Cyan
        Write-Host "`tTo: " -NoNewline
        Write-Host $OutPath -ForegroundColor Cyan

        ## Clear existing files from the output folder
        if ($ClearExistingFiles) {
            Write-Host 'Export is Clearing Existing files before writing!!' -ForegroundColor Magenta

            ## Delete Files
            $ExistingFiles = Get-ChildItem -Path (Join-Path $OutPath $Name '_REFERENCE DESIGN') -Recurse -File -Force -ErrorAction SilentlyContinue
            foreach ($ExistingFile in $ExistingFiles) {
                Write-Verbose "Removing Old File: $($ExistingFile.Name)"
                Remove-Item $ExistingFile -Force -Recurse
            }

            ## Delete Folders
            $ExistingFolders = Get-ChildItem -Path (Join-Path $OutPath $Name '_REFERENCE DESIGN') -Recurse -Directory -Force -ErrorAction SilentlyContinue
            foreach ($ExistingFolder in $ExistingFolders) {
                Write-Verbose "Removing Old File: $($ExistingFolder.Name)"
                Remove-Item $ExistingFolder -Force -Recurse -ErrorAction 'SilentlyContinue'
            }
        }

        $FilterByProvider = $false
        Write-Host "`tProviders:`t" -NoNewline
        if ($ProviderName) {
            Write-Host $ProviderName -ForegroundColor Cyan
            $FilterByProvider = $true
        } else {
            Write-Host 'All Providers' -ForegroundColor Cyan
        }
    }

    process {
        # Set up the directory structure for all of the output files
        $OutputDirectory = Join-Path $OutPath $Name
        $ExtensionDirectory = Join-Path $OutputDirectory '_REFERENCE DESIGN'
        $ExtensionDataDirectory = Join-Path $OutputDirectory '_REFERENCE DATA'

        Test-FolderPath $ExtensionDirectory
        Test-FolderPath (Join-Path $OutputDirectory 'Documentation')
        Test-FolderPath (Join-Path $OutputDirectory '_REFERENCE DATA')

        ##
        ## Export all of the components
        ##

        # Export the Dependency Types
        if ($Components.DependencyTypes) {
            Write-Host 'Exporting Dependency Types...' -NoNewline
            $DependencyTypesFolderPath = Join-Path $ExtensionDirectory 'DependencyTypes'
            Test-FolderPath -FolderPath $DependencyTypesFolderPath

            $DependencyTypes = Get-TMDependencyType -ResetIDs -TMSession $TMSession
            if (!$DependencyTypes) {
                Write-Host "`tNo Dependency Types to export"
            } else {
                $DependencyTypes | ForEach-Object {
                    if (-Not [string]::IsNullOrWhiteSpace($_.label.Trim())) {
                        $Filename = Get-FilenameSafeString -String $_.label
                        $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $DependencyTypesFolderPath "$Filename.json") -Force
                    }
                }
                Write-Host "`t$($DependencyTypes.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Dependency Type(s) exported'
            }
        }

        # Export the App Types
        if ($Components.AppTypes) {
            Write-Host "Exporting App Types...`t" -NoNewline
            $AppTypesFolderPath = Join-Path $ExtensionDirectory 'AppTypes'
            Test-FolderPath -FolderPath $AppTypesFolderPath

            $AppTypes = Get-TMAssetOption -Type 'App Type' -ResetIDs -TMSession $TMSession
            if (!$AppTypes) {
                Write-Host "`tNo App Types to export"
            } else {
                $AppTypes | ForEach-Object {
                    if (-Not [string]::IsNullOrWhiteSpace($_.label.Trim())) {
                        $Filename = Get-FilenameSafeString -String $_.label
                        $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $AppTypesFolderPath "$Filename.json") -Force
                    }
                }
                Write-Host "`t$($AppTypes.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'App Type(s) exported'
            }
        }

        # Export the Device Types
        if ($Components.DeviceTypes) {
            Write-Host 'Exporting Device Types...' -NoNewline
            $DeviceTypesFolderPath = Join-Path $ExtensionDirectory 'DeviceTypes'
            Test-FolderPath -FolderPath $DeviceTypesFolderPath

            $DeviceTypes = Get-TMAssetOption -Type 'Asset Type' -ResetIDs -TMSession $TMSession
            if (!$DeviceTypes) {
                Write-Host "`tNo Device Types to export"
            } else {
                $DeviceTypes | ForEach-Object {
                    if (-Not [string]::IsNullOrWhiteSpace($_.label.Trim())) {
                        $Filename = Get-FilenameSafeString -String $_.label
                        $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $DeviceTypesFolderPath "$Filename.json") -Force
                    }
                }
                Write-Host "`t$($DeviceTypes.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Device Type(s) exported'
            }
        }

        # Export the Task Categories
        if ($Components.TaskCategories) {
            Write-Host 'Exporting Task Categories...' -NoNewline
            $TaskCategoriesFolderPath = Join-Path $ExtensionDirectory 'TaskCategories'
            Test-FolderPath -FolderPath $TaskCategoriesFolderPath

            $TaskCategories = Get-TMAssetOption -Type 'Task Category' -ResetIDs -TMSession $TMSession
            if (!$TaskCategories) {
                Write-Host "`tNo Task Categories to export"
            } else {
                $TaskCategories | ForEach-Object {
                    if (-Not [string]::IsNullOrWhiteSpace($_.label.Trim())) {
                        $Filename = Get-FilenameSafeString -String $_.label
                        $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $TaskCategoriesFolderPath "$Filename.json") -Force
                    }
                }
                Write-Host "`t$($TaskCategories.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Task Categories exported'
            }
        }

        # Export the Field Specs
        if ($Components.FieldSpecs) {
            Write-Host 'Exporting Field Specs...' -NoNewline
            $FieldSpecs = Get-TMFieldSpecs -ResetIDs -CustomOnly -TMSession $TMSession
            if (!$FieldSpecs) {
                Write-Host "`tNo Asset Field Specs to export"
            } else {
                $FieldSpecsFolderPath = Join-Path $ExtensionDirectory 'FieldSpecs'
                Test-FolderPath -Path (Join-Path $FieldSpecsFolderPath 'Shared')
                Test-FolderPath -Path (Join-Path $FieldSpecsFolderPath 'Application')
                Test-FolderPath -Path (Join-Path $FieldSpecsFolderPath 'Database')
                Test-FolderPath -Path (Join-Path $FieldSpecsFolderPath 'Device')
                Test-FolderPath -Path (Join-Path $FieldSpecsFolderPath 'Storage')

                ## Iterate through each Domain Class
                ##### This is done in this order expressly expressly because shared fields will be UPDATED because it exists in each domain.
                ##### This order ensures that if there is variation in the color/order, etc. Application will win.
                ##### This is because the Shared fields are inserted with ONE configuration across each domain.
                $DomainClasses = @('STORAGE', 'DATABASE', 'DEVICE', 'APPLICATION')
                foreach ($DomainClass in $DomainClasses) {

                    ## Iterate over each Domain Field
                    $DomainFields = $FieldSpecs.$DomainClass.fields
                    foreach ($DomainField in $DomainFields) {

                        # $FieldFileName = Join-Path $FieldSpecsFolderPath $DomainClass "$($DomainField.order)-$($DomainField.label).json"
                        $FieldFileName = Join-Path $FieldSpecsFolderPath ($DomainField.shared -eq 1 ? 'Shared' : $DomainClass) "$($DomainField.order)-$($DomainField.label).json"
                        Set-Content -Path $FieldFileName -Value ($DomainField | ConvertTo-Json -Depth 5) -Force
                    }
                }
                Write-Host "`tAsset Field Specs exported"
            }
        }

        # Export the Bundles
        if ($Components.Bundles) {
            Write-Host "Exporting Bundles...`t" -NoNewline
            $BundlesFolderPath = Join-Path $ExtensionDirectory 'Bundles'
            Test-FolderPath -FolderPath $BundlesFolderPath

            $Bundles = Get-TMBundle -ResetIDs -TMSession $TMSession
            if (!$Bundles) {
                Write-Host "`tNo Bundles to export"
            } else {
                $Bundles | ForEach-Object {
                    $Filename = Get-FilenameSafeString -String $_.Name
                    $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $BundlesFolderPath "$Filename.json") -Force
                }
                Write-Host "`t$($Bundles.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Bundle(s) exported'
            }
        }

        # Export the Events
        if ($Components.Events) {
            Write-Host "Exporting Events...`t" -NoNewline
            $EventsFolderPath = Join-Path $ExtensionDirectory 'Events'
            Test-FolderPath -FolderPath $EventsFolderPath

            $Events = Get-TMEvent -ResetIDs -TMSession $TMSession
            if (!$Events) {
                Write-Host "`tNo Events to export"
            } else {
                $Events | ForEach-Object {
                    $Filename = Get-FilenameSafeString -String $_.Name
                    $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $EventsFolderPath "$Filename.json") -Force
                }
                Write-Host "`t$($Events.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Event(s) exported'
            }
        }

        # Export the Teams
        if ($Components.Teams) {
            Write-Host "Exporting Teams...`t" -NoNewline
            $TeamsFolderPath = Join-Path $ExtensionDirectory 'Teams'
            Test-FolderPath -FolderPath $TeamsFolderPath

            $Teams = Get-TMTeam -TMSession $TMSession
            if (!$Teams) {
                Write-Host "`tNo Teams to export"
            } else {
                $Teams | ForEach-Object {
                    $Filename = Get-FilenameSafeString -String $_.Code
                    $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $TeamsFolderPath "$Filename.json") -Force
                }
                Write-Host "`t$($Teams.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Team(s) exported'
            }
        }

        # Export the Providers
        if ($Components.Providers) {
            Write-Host "Exporting Providers...`t" -NoNewline
            $ProvidersFolderPath = Join-Path $ExtensionDirectory 'Providers'
            Test-FolderPath -FolderPath $ProvidersFolderPath

            $Providers = Get-TMProvider -ResetIDs -TMSession $TMSession
            if (!$Providers) {
                Write-Host "`tNo Providers to export"
            } else {
                if ($FilterByProvider) {
                    $Providers = $Providers | Where-Object Name -In $ProviderName
                }
                $Providers | ForEach-Object {
                    $Filename = Get-FilenameSafeString -String $_.Name
                    $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $ProvidersFolderPath "$Filename.json") -Force
                }
                Write-Host "`t$($Providers.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Provider(s) exported'
            }
        }

        # Export the Actions
        if ($Components.Actions) {

            Write-Host "Exporting Actions...`t" -NoNewline
            $ActionsFolderPath = Join-Path $ExtensionDirectory 'Actions'
            Test-FolderPath $ActionsFolderPath
            $Actions = Get-TMAction -SaveCodePath $ActionsFolderPath -ProviderName $ProviderName -ResetIDs -Passthru -TMSession $TMSession
            if (!$Actions) {
                Write-Host "`tNo Actions to export"
            } else {
                Write-Host "`t$($Actions.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Action(s) exported'
            }
        }

        # Export the DataScript Scripts
        if ($Components.DataScripts) {

            Write-Host 'Exporting DataScripts...' -NoNewline
            $DataScriptsFolderPath = Join-Path $ExtensionDirectory 'DataScripts'
            Test-FolderPath $DataScriptsFolderPath
            $DataScripts = Get-TMDatascript -ResetIDs -SaveCodePath $DataScriptsFolderPath -ProviderName $ProviderName -Passthru -TMSession $TMSession
            if (!$DataScripts) {
                Write-Host "`tNo Datascripts to export"
            } else {
                # TODO: Is the 'Private' folder supposed to be excluded?
                Write-Host "`t$($DataScripts.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Datascript(s) exported'
            }
        }

        # Export the Recipes
        if ($Components.Recipes) {

            Write-Host "Exporting Recipes...`t" -NoNewline
            $RecipesFolderPath = Join-Path $ExtensionDirectory 'Recipes'
            Test-FolderPath $RecipesFolderPath
            $Recipes = Get-TMRecipe -ResetIDs -SaveCodePath $RecipesFolderPath -Passthru -TMSession $TMSession
            if (!$Recipes) {
                Write-Host "`tNo Recipes to export"
            } else {
                Write-Host "`t$($Recipes.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Recipe(s) exported'
            }
        }

        # Export the Tags
        if ($Components.Tags) {
            Write-Host "Exporting Tags...`t" -NoNewline
            $TagsFolderPath = Join-Path $ExtensionDirectory 'Tags'
            Test-FolderPath -FolderPath $TagsFolderPath

            $Tags = Get-TMTag -ResetIDs -TMSession $TMSession
            if (!$Tags) {
                Write-Host "`tNo Tags to export"
            } else {
                $Tags | ForEach-Object {
                    $Filename = Get-FilenameSafeString -String $_.Name
                    $_ | ConvertTo-Json -Depth 100 | Set-Content -Path (Join-Path $TagsFolderPath "$Filename.json") -Force
                }
                Write-Host "`t$($Tags.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'Tags(s) exported'
            }
        }

        # Export the AssetViews
        if ($Components.AssetViews) {
            Write-Host "Exporting AssetViews...`t" -NoNewline
            $AssetViewsFolderPath = Join-Path $ExtensionDirectory 'AssetViews'
            Test-FolderPath -FolderPath $AssetViewsFolderPath

            $AssetViews = Get-TMAssetViewConfiguration -ResetIDs -TMSession $TMSession -ExcludeSystem
            if (!$AssetViews) {
                Write-Host "`tNo AssetViews to export"
            } else {

                ## Get a FieldToLabel map to build string replacements
                $LabelReplacements = [System.Collections.ArrayList]@()
                $FieldToLabelMap = Get-TMFieldToLabelMap

                ## Create a replacement token for each asset/label = field set
                foreach ($DomainClass in @('DEVICE', 'APPLICATION', 'DATABASE', 'STORAGE' )) {

                    foreach ($FieldName in $FieldToLabelMap.$DomainClass.Keys) {
                        if ($FieldName -match 'custom\d+') {

                            # Write-Host $FieldName
                            [void]($LabelReplacements.Add([pscustomobject]@{
                                        DomainClass = $DomainClass
                                        FieldLabel  = $FieldToLabelMap.$DomainClass.$FieldName
                                        FieldName   = $FieldName
                                    }
                                )
                            )
                        }
                    }
                }

                $AssetViews | ForEach-Object {
                    $AssetViewName = $_.name

                    ## Replace all customN in the JSON Data
                    $SourceCodeLines = ($_ | ConvertTo-Json -Depth 10) -split "`n"
                    $UpdatedSourceCodeLines = [System.Collections.ArrayList]::new()
                    foreach ($SourceCodeLine in $SourceCodeLines) {
                        $CurrentLine = $SourceCodeLine
                        $LabelReplacements | ForEach-Object {
                            if ($CurrentLine -match $_.FieldName) {
                                $CurrentLine = $CurrentLine -replace $_.FieldName, "customN|$($_.DomainClass)|$($_.FieldLabel)|"
                            }
                        }
                        [void]($UpdatedSourceCodeLines.Add($CurrentLine))
                    }
                    $UpdatedSourceCodeLines -join "`n" | Set-Content -Path (Join-Path $AssetViewsFolderPath "$AssetViewName.json") -Force
                }
                Write-Host "`t$($AssetViews.Count) " -NoNewline -ForegroundColor DarkBlue
                Write-Host 'AssetView(s) exported'
            }
        }

        # Export Asset Data
        if ($Components.AssetData) {
            Write-Host 'Exporting Asset Data...' -NoNewline
            Export-TMExcel -Path $ExtensionDataDirectory -TMSession $TMSession
            Write-Host "`t`tAsset Data exported"
        }

        Write-Host 'Creating package.json file...'
        New-TMExtensionPackageFile -Name $Name -Path $OutputDirectory
    }
}

function New-TMExtensionPackageFile {
    <#
    .SYNOPSIS
    Creates a new package.json file for a locally downloaded/exported Reference Design

    .DESCRIPTION
    This function will look at the

    .PARAMETER Name
    Parameter description

    .PARAMETER Path
    Parameter description

    .PARAMETER Description
    Parameter description

    .PARAMETER Author
    Parameter description

    .PARAMETER Email
    Parameter description

    .PARAMETER Passthru
    A switch indicating that the created package object should be sent back
    to the caller

    .EXAMPLE
    New-TMExtensionPackageFile -Name 'TM - Rules Engine' -Path 'C:\DEV\Downloaded Reference Design'

    .EXAMPLE
    $PackageSplat = @{
        Name = VMware - vCenter'
        Path = 'C:\Users\user\TMD_Files\Reference Designs\Downloaded\VMware - vCenter'
        Description = 'This is a detailed description of the Reference Design'
        Author = 'Me'
        Email = 'me@tdsi.com'
    }
    New-TMExtensionPackageFile @PackageSplat

    .EXAMPLE
    $ExtensionPackage = New-TMExtensionPackageFile -Name 'New Extension' -Path 'C:\DEV\Extension' -Passthru
    Write-Host "There are $($ExtensionPackage.Inventory.actions.Count) action(s) included in this Reference Design"

    .OUTPUTS
    A [PSCustomObject] if -Passthru is specified, otherwise nothing
    #>


    [alias('New-TMReferenceDesignPackageFile')]
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [String]$Name,

        [Parameter(Mandatory = $true, Position = 1)]
        [ValidateScript( { (Get-Item $_) -is [System.IO.DirectoryInfo] })]
        [String]$Path,

        [Parameter(Mandatory = $false, Position = 2)]
        [String]$Description,

        [Parameter(Mandatory = $false, Position = 3)]
        [String]$Author,

        [Parameter(Mandatory = $false, Position = 4)]
        [String]$Email,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru

    )

    $Inventory = @{
        Artifacts       = [System.Collections.ArrayList]::new()
        ArtifactLinks   = [System.Collections.ArrayList]::new()
        Actions         = [System.Collections.ArrayList]::new()
        DataScripts     = [System.Collections.ArrayList]::new()
        Recipes         = [System.Collections.ArrayList]::new()
        Bundles         = [System.Collections.ArrayList]::new()
        Providers       = [System.Collections.ArrayList]::new()
        DependencyTypes = [System.Collections.ArrayList]::new()
        FieldSpecs      = @{}
    }
    $ExtensionPath = Join-Path $Path '_REFERENCE DESIGN'

    ## Read the Actions Folder to get the name of Scripts
    $ActionFiles = Get-ChildItem -Path (Join-Path $ExtensionPath 'Actions') -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '*.ps1' }
    foreach ($ActionFile in $ActionFiles) {

        ## Convert the Script into a proper ActionObject
        $Action = Read-TMActionScriptFile -Path $ActionFile.FullName

        ## Some files are not setup or created with all of the metadata. Fill in details based on the filename.
        if (-Not $Action.Name) {

            ## Add this Action to the Actions array for writing to JSON
            [void]$Inventory.Actions.Add(
                [PSCustomObject]@{
                    name        = $ActionFile.BaseName
                    description = ''
                }
            )
        } else {

            ## Add this Action to the Actions array for writing to JSON
            [void]$Inventory.Actions.Add(
                [PSCustomObject]@{
                    name        = $Action.Name
                    description = $Action.Description
                }
            )
        }
    }

    ## Read the DataScript Scripts Folder to get the name Scripts
    if (Test-Path($ExtensionPath + '\DataScripts')) {
        $DataScriptFiles = Get-ChildItem -Path (Join-Path $ExtensionPath 'DataScripts') -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '*.groovy' }
    } elseif (Test-Path($ExtensionPath + '\ETL')) {
        $DataScriptFiles = Get-ChildItem -Path (Join-Path $ExtensionPath 'ETL') -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '*.groovy' }
    }

    foreach ($DataScriptFile in $DataScriptFiles) {

        ## Convert the Script into a proper TMDatascript Object
        $DataScript_File = Read-TMDatascriptFile -Path $DataScriptFiles.FullName -ErrorAction 'SilentlyContinue'

        ## Some files are not setup or created with all of the metadata. Fill in details based on the filename.
        if (-Not $DataScript_File) {
            [void]$Inventory.DataScripts.Add(
                [PSCustomObject]@{
                    name        = $DataScript_File.name
                    description = ''
                }
            )
        } else {

            ## Add this DataScript Script to the array for writing to JSON
            [void]$Inventory.DataScripts.Add(
                [PSCustomObject]@{
                    name        = $DataScript_File.name
                    description = $DataScript_File.description
                }
            )
        }
    }

    ## Read the Recipes Folder to get the name Scripts
    $RecipeFiles = Get-ChildItem -Path (Join-Path $ExtensionPath 'Recipes') -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '*.json' }
    foreach ($RecipeFile in $RecipeFiles) {

        ## Convert the Script into a proper TMRecipeScript Object
        $Recipe = Read-TMRecipeScriptFile -Path $RecipeFile.FullName

        ## Some files are not setup or created with all of the metadata. Fill in details based on the filename.
        if (-Not $Recipe) {
            ## Add this Recipe Script to the array for writing to JSON
            [void]$Inventory.Recipes.Add(
                [PSCustomObject]@{
                    name        = $RecipeFile.name
                    description = $RecipeFile.description
                }
            )
        } else {

            ## Add this Recipe Script to the array for writing to JSON
            [void]$Inventory.Recipes.Add(
                [PSCustomObject]@{
                    name        = $Recipe.name
                    description = $Recipe.description
                }
            )
        }
    }

    # Get the bundles to add to the inventory
    $BundleFile = Join-Path $ExtensionPath 'Bundles.json'
    if (Test-Path -Path $BundleFile) {
        Get-Content -Path $BundleFile | ConvertFrom-Json | ForEach-Object {
            [void]$Inventory.Bundles.Add(
                [PSCustomObject]@{
                    name        = $_.name
                    description = $_.description
                }
            )
        }
    }

    # Get the providers to add to the inventory
    $ProvidersFile = Join-Path $ExtensionPath 'Providers.json'
    if (Test-Path $ProvidersFile -ErrorAction SilentlyContinue) {
        Get-Content -Path $ProvidersFile | ConvertFrom-Json | ForEach-Object {
            [void]$Inventory.Providers.Add(
                [PSCustomObject]@{
                    name        = $_.name
                    description = $_.description
                }
            )
        }
    }

    # Get the Dependency Types to add to the inventory
    $DependencyTypesFile = Join-Path $ExtensionPath 'DependencyTypes.json'
    if (Test-Path $DependencyTypesFile -ErrorAction SilentlyContinue) {
        Get-Content -Path $DependencyTypesFile | ConvertFrom-Json | ForEach-Object {
            [void]$Inventory.DependencyTypes.Add($_.label)
        }
    }

    ## Check Extension Package v3 (Folder of Files)
    $FieldSpecsFolderPath = Join-Path $ExtensionPath 'FieldSpecs'
    if(Test-Path $FieldSpecsFolderPath -ErrorAction SilentlyContinue){

        ## Create the FieldSpecs Object to add all of the fields to
        $FieldSpecs = [pscustomobject]@{
            APPLICATION = [PSCustomObject]@{
                lastUpdated = ''
                dateCreated = ''
                domain = 'APPLICATION'
                fields = @()
                version = 1
            }
            DATABASE = [PSCustomObject]@{
                lastUpdated = ''
                dateCreated = ''
                domain = 'DATABASE'
                fields = @()
                version = 1
            }
            DEVICE = [PSCustomObject]@{
                lastUpdated = ''
                dateCreated = ''
                domain = 'DEVICE'
                fields = @()
                version = 1
            }
            STORAGE = [PSCustomObject]@{
                lastUpdated = ''
                dateCreated = ''
                domain = 'STORAGE'
                fields = @()
                version = 1
            }
        }

        ## Handle Single JSON field files from folders
        $SharedFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Shared') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
        foreach ($FieldFile in $SharedFieldFiles) {
            $FieldSpecs.APPLICATION.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
            $FieldSpecs.DATABASE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
            $FieldSpecs.DEVICE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
            $FieldSpecs.STORAGE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
        }

        $ApplicationFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Application') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
        foreach ($FieldFile in $ApplicationFieldFiles) {
            $FieldSpecs.APPLICATION.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
        }

        $DatabaseFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Database') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
        foreach ($FieldFile in $DatabaseFieldFiles) {
            $FieldSpecs.DATABASE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
        }

        $DeviceFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Device') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
        foreach ($FieldFile in $DeviceFieldFiles) {
            $FieldSpecs.DEVICE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
        }

        $StorageFieldFiles = Get-ChildItem -Path (Join-Path $FieldSpecsFolderPath 'Storage') -Filter '*.json' -Force -ErrorAction 'SilentlyContinue'
        foreach ($FieldFile in $StorageFieldFiles) {
            $FieldSpecs.STORAGE.fields += (Get-Content -Path $FieldFile.FullName | ConvertFrom-Json)
        }

    } else {

        ## Check Extension Package <v3 (Single FieldSpecs.json file)
        $FieldSpecsFilePath = Join-Path $ExtensionPath 'FieldSpecs.json'
        if (Test-Path $FieldSpecsFilePath -ErrorAction SilentlyContinue) {

            $TMVersion = [Version]::parse($TMSessionConfig.TMVersion)

            ## Version 6.0.2.1+ (and TODO version 6.1?, 5x?)
            ## Requires the class names to be lower case
            if ($TMVersion.Major -eq 6 -and $TMVersion -ge '6.1.0') {
                ## Convert each Asset Class name to lowercase
                $FieldSpecsData = ((Get-Content -Path $FieldSpecsFilePath) -replace 'constraints', 'constraint')
            } else {
                ## No conversion is necessary, assign the provided fields as the updates
                $FieldSpecsData = (((Get-Content -Path $FieldSpecsFilePath) -replace 'constraint', 'constraints') -replace 'constraintss', 'constraints')
            }
        }
        $FieldSpecs = $FieldSpecsData | ConvertFrom-Json
    }

    ## Set the Collected field specs to the Inventory data
    $Inventory.FieldSpecs = $FieldSpecs

    # Create the package object which will be written to a file
    $Package = [PSCustomObject]@{
        name        = $Name.ToLower().Replace(' - ', '-').Replace(' ', '-')
        version     = '1.0.0'
        productName = $Name
        description = $Description ?? ''
        homepage    = ''
        email       = $Email ?? ''
        author      = $Author ?? ''
        published   = $false
        extension   = @{
            packageFormatVersion = 3
            dependencies         = @{
                installedApplications = @(
                    @{
                        name    = 'PowerShell'
                        type    = 'Software'
                        version    = "^$($PSVersionTable.PSVersion.ToString())"
                        source  = 'https://www.github.com/TransitionManager/TMD-Resources/PowerShell'
                    }
                )
                powershellModules     = @(
                    @{
                        name    = '<PLACEHOLDER>'
                        version = '1.0.0'
                        source  = ''
                    }
                )
                extensions            = @(
                    @{
                        name    = '<PLACEHOLDER>'
                        version = '1.0.0'
                    }
                )
            }
        }
        inventory   = $Inventory
    }

    # Create the file
    $Package | ConvertTo-Json -Depth 5 | Set-Content -Path (Join-Path $Path 'package.json') -Force

    # Send the package back if Passthru was specified
    if ($Passthru) {
        $Package
    }
}

function New-TMExtensionInventory {
    <#
    .SYNOPSIS
    Creates a new inventory.json file with all of the configuration assets it contains

    .DESCRIPTION
    This function will collect all of the TM Server/Project configuration artifiacts to an inventory.json file



    .PARAMETER TMSession
    The TM Session to use

    .PARAMETER Path
    Output folder or file path for the inventory file. Include '.json' in the file name to create that file, otherwise the path is used as a Directory.

    .PARAMETER Passthru
    Return the TMConfigInventory File

    .EXAMPLE
    New-TMConfigInventory -TMProfile Default -Path 'C:\Temp\testfile.json'

    .OUTPUTS
    A [PSCustomObject] if -Passthru is specified, otherwise nothing
    #>


    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = 'Default',

        [Parameter(Mandatory = $false)]
        [String]$InventoryPath,

        [Parameter(Mandatory = $false)]
        [String]$Server = $global:TMSessions[$TMSession].TMServer,

        [Parameter(Mandatory = $false, Position = 1)]
        [String]$OutPath,
        # (

        <#
            ## Root the folder on the User's Reference Design folder
            $UserPaths.referencedesigns

            ## Add a directory for the Server
            $Server

            ## Add a Folder for the TM Project
            $global:TMSessions[$TMSession].UserContext.Project.Name

            ## Name the file
            'Inventory.json'
            #>


        # Join-Path $UserPaths.referencedesigns $Server $global:TMSessions[$TMSession].UserContext.Project.Name 'Inventory.json'
        # ),

        [Parameter(Mandatory = $false)]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru

    )

    ## Test the optional input file path
    if ($OutPath) {

        ## Test if a Json file was named
        if ($OutPath -like '*.json') {

            ## Parse the path
            $ParentDirectory = Split-Path -Path $OutPath -Parent
            Test-FolderPath -FolderPath $ParentDirectory

        } elseif (-not ([String]::IsNullOrWhiteSpace($OutPath))) {
            Test-FolderPath -FolderPath $OutPath
            $OutPath += (Join-Path $OutPath 'Inventory.json').FullName
        }
    }


    ## Get Session Configuration
    $TMSessionConfig = $global:TMSessions[$TMSession]
    if (-not $TMSessionConfig) {
        Write-Host 'TMSession: [' -NoNewline
        Write-Host $TMSession -ForegroundColor Cyan
        Write-Host '] was not Found. Please use the New-TMSession command.'
        Throw 'TM Session Not Found. Use New-TMSession command before using features.'
    }

    ##
    ## Collect the Inventory
    ##

    ## Read the inventory path if there is one provided
    if (Test-Path $InventoryPath -ErrorAction SilentlyContinue) {
        try {
            $Data = Get-Content $InventoryPath | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
        } catch {
            Write-Host 'The Inventory file could not be converted from json. Performing new Inventory using the TM Server settings supplied' -ForegroundColor Yellow
        }
    }

    ## Allow reading from a server connection, if no Inventory was provided
    if (-Not $Data) {

        ## Create the inventory Package
        $Data = @{
            Inventory     = @{

                ## Add Useful Data
                TMServer        = $TMServer
                TMProject       = $TMProject
                DateCollected   = (Get-Date).ToLongDateString()

                actions         = [System.Collections.ArrayList]::new()
                dataScripts     = [System.Collections.ArrayList]::new()
                recipes         = [System.Collections.ArrayList]::new()
                bundles         = [System.Collections.ArrayList]::new()
                providers       = [System.Collections.ArrayList]::new()
                dependencyTypes = [System.Collections.ArrayList]::new()
                fieldSpecs      = @{}
                Artifacts       = [System.Collections.ArrayList]::new()
                ArtifactLinks   = [System.Collections.ArrayList]::new()
            }

            Relationships = @{
                Providers       = @{}
                Actions         = @{}
                DataScripts     = @{}
                Recipes         = @{}
                Bundles         = @{}
                Fields          = @{}
                DependencyTypes = @{}
            }
        }

        ## Add a 'TM Server'
        [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                Id   = "tmserver-$TMServer"
                Type = 'TMServer'
                Name = $TMServer
            }
        )
        ## Add a 'TM Project'
        [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                Id       = "tmproject-$TMProject"
                Type     = 'TMProject'
                Name     = $TMProject

                ParentId = $TMServer
            }
        )

        ## Collect FieldSpecs
        $Inventory.fieldSpecs = Get-TMFieldSpecs -TMSession $TMSession

        ## Add a 'FieldSpecs' object to the Artifact inventory (for proper diagram structuring)
        [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                Id       = 'tmfieldspecs'
                Type     = 'FieldSpecs'
                Name     = 'FieldSpecs'

                ParentId = "tmproject-$TMProject"
            }
        )

        ## Process each Domain Class
        foreach ($DomainClass in $Inventory.fieldSpecs.PSobject.Properties.Name) {
            ## Add an Artifact to the inventory
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmfieldspecdomain-$DomainClass"
                    Type     = 'FieldSpecDomain'
                    Name     = $DomainClass

                    ParentId = 'tmfieldspecs'
                }
            )
            ## Handle Each Domain Class field
            $ClassFields = $Inventory.fieldSpecs.$DomainClass.fields
            foreach ($Field in $ClassFields) {

                ## Add a property for this Field in the Relationships data
                $Data.Relationships.Fields.("$($DomainClass)-$($Field.label)") = @{
                    Actions         = [System.Collections.ArrayList]@()
                    DataScripts     = [System.Collections.ArrayList]@()
                    Recipes         = [System.Collections.ArrayList]@()
                    RecipeGroups    = [System.Collections.ArrayList]@()
                    RecipeTaskSpecs = [System.Collections.ArrayList]@()
                }

                ## Add a AssetClass for each domain to the inventory
                [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                        Id          = "tmassetfield-$($DomainClass)-$($Field.label)"
                        Type        = 'AssetField'
                        Name        = $Field.label

                        Constraints = $Field.constraints
                        DomainClass = $DomainClass
                        ParentId    = "tmfieldspecdomain-$DomainClass"
                    }
                )
            }
        }

        ## Collect Actions
        $Inventory.actions = Get-TMAction -Passthru -TMSession $TMSession
        foreach ($Item in $Inventory.actions) {

            ## Add a property for this Field in the Relationships data
            $Data.Relationships.Actions.($Item.name) = @{
                Fields          = [System.Collections.ArrayList]@()
                Recipes         = [System.Collections.ArrayList]@()
                RecipeTaskSpecs = [System.Collections.ArrayList]@()
            }

            ## Add an Artifact to the inventory
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmaction-$($Item.id)"
                    Type     = 'Action'
                    Name     = $Item.name

                    ParentId = "tmprovider-$($item.provider.id)"
                }
            )
        }

        ## Collect Data Scripts
        $Inventory.dataScripts = Get-TMDatascript -Passthru -TMSession $TMSession
        foreach ($Item in $Inventory.dataScripts) {

            ## Add a property for this Field in the Relationships data
            $Data.Relationships.DataScripts.($Item.name) = @{
                Fields = [System.Collections.ArrayList]@()
            }

            ## Add an Artifact to the inventory
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmdatascript-$($Item.id)"
                    Type     = 'DataScript'
                    Name     = $Item.name

                    ParentId = "tmprovider-$($item.provider.id)"
                }
            )
        }

        ## Collect Recipes
        $Inventory.recipes = Get-TMRecipe -AsJson -Passthru -TMSession $TMSession
        foreach ($Item in $Inventory.recipes) {

            ## Add a property for this Field in the Relationships data
            $Data.Relationships.Recipes.($Item.name) = @{
                Actions         = [System.Collections.ArrayList]@()
                RecipeGroups    = [System.Collections.ArrayList]@()
                RecipeTaskSpecs = [System.Collections.ArrayList]@()
                Fields          = [System.Collections.ArrayList]@()
            }

            ## Add an Artifact to the inventory
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmrecipe-$($Item.id)"
                    Type     = 'Recipe'
                    Name     = $Item.name

                    ParentId = "tmprovider-$($item.provider.id)"
                }
            )
        }

        ## Collect Bundles
        $Inventory.bundles = Get-TMBundle -TMSession $TMSession
        foreach ($Item in $Inventory.bundles) {

            ## Add an Artifact to the inventory
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmbundle-$($Item.id)"
                    Type     = 'Bundle'
                    Name     = $Item.name

                    ParentId = "tmproject-$TMProject"
                }
            )
        }

        ## Collect Providers
        $Inventory.providers = Get-TMProvider -TMSession $TMSession
        foreach ($Item in $Inventory.providers) {

            ## Add an Artifact to the inventory
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmprovider-$($Item.id)"
                    Type     = 'Provider'
                    Name     = $Item.name

                    ParentId = "tmproject-$TMProject"
                }
            )

            ## Add a Provider-Actions Artifact
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmprovider-actions-$($Item.id)"
                    Type     = 'ProviderActions'
                    Name     = $Item.name + ' Actions'

                    ParentId = "tmprovider-$($Item.id)"
                }
            )

            ## Add a Provider-Actions Artifact
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmprovider-datascripts-$($Item.id)"
                    Type     = 'ProviderActions'
                    Name     = $Item.name + ' Data Scripts'

                    ParentId = "tmprovider-$($Item.id)"
                }
            )
        }

        ## Collect Dependency Types
        $Inventory.dependencyTypes = Get-TMDependencyType -TMSession $TMSession
        foreach ($Item in $Inventory.dependencyTypes) {

            ## Add an Artifact to the inventory
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmdependencytype-$($Item.label)"
                    Type     = 'DependencyType'
                    Name     = $Item.label

                    ParentId = "tmserver-$TMServer"
                }
            )
        }

        ##
        ## Save the Inventory data for convenience
        ##
        if (-Not ([String]::IsNullOrWhiteSpace($InventoryPath))) {
            $Data | ConvertTo-Json -Depth 100 -Compress | Set-Content -Path $InventoryPath -Force
        }
    }

    ##
    ## Calculate the Artifact Relationships
    ##

    ## ACTION(parameter) > Asset Field
    foreach ($Action in $Inventory.actions) {

        if ($Action.MethodParams) {

            ## Iterater on each Method Parameter
            foreach ($Param in $Action.methodParams) {

                ## only map params that use a field label
                if ($Param.context -ne 'USER_DEF' -and $Param.fieldLabel) {

                    ## Record the connection in the hashmap
                    [void]($Data.Relationships.Actions.($Action.Name).Fields.Add("$($Param.context)-$($Param.fieldLabel)"))

                    ## Add the Artifact Link
                    [void]$Inventory.ArtifactLinks.Add([PSCustomObject]@{
                            Id   = "tmaction-$($Action.Id)-tmassetfield-$($Param.context)-$($Param.fieldLabel)"
                            From = "tmaction-$($Action.Id)"
                            To   = "tmassetfield-$($Param.context)-$($Param.fieldLabel)"
                            type = 'TM Server hosts Project'
                        }
                    )
                }
            }
        }
    }

    ## Recipe > Actions, Groups, TaskSpecs
    foreach ($Recipe in $Inventory.recipes) {

        ## Create a Groups object
        [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                Id       = "tmrecipe-$($Recipe.id)-groups"
                Type     = 'RecipeGroup'
                Name     = $Recipe.name + ' Groups'

                ParentId = "tmrecipe-$($Recipe.id)"
            }
        )

        ## Create a TaskSpecs object
        [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                Id       = "tmrecipe-$($Recipe.id)-taskspecs"
                Type     = 'RecipeGroup'
                Name     = $Recipe.name + ' Groups'

                ParentId = "tmrecipe-$($Recipe.id)"
            }
        )

        ## Check each Group in the recipe
        foreach ($Group in $Recipe.sourceCodeJson.groups) {

            ## Record the connection in the hashmap
            [void]($Data.Relationships.Recipes.($Recipe.Name).RecipeGroups.Add($Group.name))

            ## Record the Group
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmrecipegroup-$($Recipe.id)-$($group.name)"
                    Type     = 'RecipeGroup'
                    Name     = $group.name

                    ParentId = "tmrecipe-$($Recipe.id)-groups"
                }
            )

            ## TODO - Add Group Asset Field resolution so the groups can be bound to the Asset-Fields
        }

        ## Check each Task Spec in the recipe
        foreach ($TaskSpec in $Recipe.sourceCodeJson.tasks) {

            ## Record the connection in the hashmap
            [void]($Data.Relationships.Recipes.($Recipe.Name).RecipeTaskSpecs.Add($TaskSpec.title))

            ## Record the Task Spec
            [void]$Inventory.Artifacts.Add([PSCustomObject]@{
                    Id       = "tmtaskspec-$($Recipe.id)-$($TaskSpec.id)"
                    Type     = 'RecipeTaskSpec'
                    Name     = $TaskSpec.title

                    ParentId = "tmrecipe-$($Recipe.id)-taskspecs"
                }
            )

            ## Record Tasks that have a method assigned
            if ($TaskSpec.invoke.method) {

                ## Record the connection in the hashmap
                [void]($Data.Relationships.Recipes.($Recipe.Name).Actions.Add($TaskSpec.invoke.method))

                [void]$Inventory.ArtifactLinks.Add([PSCustomObject]@{
                        Id   = "tmaction-$($Action.Id)-tmtaskspec-$($Recipe.id)-$($TaskSpec.id)"
                        From = "tmaction-$($Action.Id)"
                        To   = "tmtaskspec-$($Recipe.id)-$($TaskSpec.id)"
                        type = 'TM Server hosts Project'
                    }
                )
            }

            ## Record Tasks that have a method assigned
            if ($TaskSpec.filter.group) {

                foreach ($Group in $TaskSpec.filter.group) {

                    ## Record the connection in the hashmap
                    [void]($Data.Relationships.Recipes.($Recipe.Name).RecipeGroups.Add($Group.name))

                    [void]$Inventory.ArtifactLinks.Add([PSCustomObject]@{
                            Id   = "tmaction-$($Action.Id)-tmtaskspec-$($Recipe.id)-$($TaskSpec.id)"
                            From = "tmaction-$($Action.Id)"
                            To   = "tmrecipegroup-$($Recipe.id)-$($group.name)"
                            type = 'TM Server hosts Project'
                        }
                    )
                }
            }
        }
    }


    ## Datascripts to
    ## > Asset Field

    # Send the package back if Passthru was specified
    if ($Passthru) {
        $Data
    }

    # ## Create a flat inventory of Artifacts


    # # Send the package back if Passthru was specified
    # if ($Passthru) {
    # $Inventory
    # }
}
function Read-TMExtensionInventory {
    <#
    .SYNOPSIS
    Creates a new inventory.json file with all of the configuration assets it contains, as read from an Extension directory

    .DESCRIPTION
    This function will read all of the TM Entities within an Extension directory

    .PARAMETER Path
    Path of the TM Extension to read

    .PARAMETER OutPath
    Filename to create containing the inventory

    .PARAMETER Passthru
    Return the TMConfigInventory File

    .EXAMPLE
    Read-TMConfigInventory -Path 'C:\Users\tbaker\TMD_Files\Reference Designs\EXTENSIONS\VMware\vCenter' -OutPath 'C:\Temp\testfile.json' -Passthru

    .OUTPUTS
    A [PSCustomObject] if -Passthru is specified, otherwise nothing
    #>


    param(

        [Parameter(Mandatory = $true, Position = 1)]
        [String]$Path,

        [Parameter(Mandatory = $false, Position = 1)]
        [String]$OutPath,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru

    )

    ## Create the inventory Package
    $Inventory = @{
        Actions         = [System.Collections.ArrayList]::new()
        DataScripts     = [System.Collections.ArrayList]::new()
        Recipes         = [System.Collections.ArrayList]::new()
        Bundles         = [System.Collections.ArrayList]::new()
        Providers       = [System.Collections.ArrayList]::new()
        DependencyTypes = [System.Collections.ArrayList]::new()
        FieldSpecs      = @{}
        Artifacts       = [System.Collections.ArrayList]::new()
        ArtifactLinks   = [System.Collections.ArrayList]::new()

        Relationships   = @{
            Providers       = @{}
            Actions         = @{}
            DataScripts     = @{}
            Recipes         = @{}
            Bundles         = @{}
            Fields          = @{}
            DependencyTypes = @{}
        }
    }

    ## Lookup the local package file to get the name and
    $PackageFilePath = "$Path\package.json"
    if (Test-Path $PackageFilePath -ErrorAction SilentlyContinue) {
        $PackageData = Get-Content -Path $PackageFilePath | ConvertFrom-Json
        $Inventory.Extension = @{
            Name        = $PackageData.name
            ProductName = $PackageData.productName
        }
    }

    ## Update the path to the internal _REFERENCE DESIGN folder
    if ($Path -notlike '*_REFERENCE DESIGN') {
        $Path = "$Path\_REFERENCE DESIGN"
    }

    ##
    ## Collect the Inventory
    ##
    #

    ## Collect JSON File data
    $ErrorActionPreference = 'SilentlyContinue'
    $Inventory.AppTypes = Get-Content (Join-Path $Path 'AppTypes.json') | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    $Inventory.Bundles = Get-Content (Join-Path $Path 'Bundles.json') | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    $Inventory.DeviceTypes = Get-Content (Join-Path $Path 'DeviceTypes.json') | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    $Inventory.Providers = Get-Content (Join-Path $Path 'Providers.json') | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    $Inventory.Tags = Get-Content (Join-Path $Path 'Tags.json') | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    $Inventory.TaskCategories = Get-Content (Join-Path $Path 'TaskCategories.json') | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    $Inventory.Teams = Get-Content (Join-Path $Path 'Teams.json') | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    $Inventory.FieldSpecs = Get-Content (Join-Path $Path 'FieldSpecs.json') | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    $ErrorActionPreference = 'Continue'

    ## Create Relationship properties for each of the fields
    # foreach ($DomainClass in $Inventory.FieldSpecs.PSobject.Properties.Name) {

    # ## Handle Each Domain Class field
    # $ClassFields = $Inventory.fieldSpecs.$DomainClass.fields
    # foreach ($Field in $ClassFields) {

    # ## Add a property for this Field in the Relationships data
    # $Inventory.Relationships.Fields.("$($DomainClass)-$($Field.label)") = @{
    # Actions = [System.Collections.ArrayList]@()
    # DataScripts = [System.Collections.ArrayList]@()
    # Recipes = [System.Collections.ArrayList]@()
    # RecipeGroups = [System.Collections.ArrayList]@()
    # RecipeTaskSpecs = [System.Collections.ArrayList]@()
    # }
    # }
    # }

    ## Create Relationship properties for each of the Providers
    # foreach ($Provider in $Inventory.Providers) {
    # $Inventory.Relationships.Providers.($Provider.Name) = @{
    # Actions = [System.Collections.ArrayList]@()
    # DataScripts = [System.Collections.ArrayList]@()
    # }
    # }

    ## Collect Actions
    $ActionFiles = Get-ChildItem -Path "$Path\Actions" -Recurse -Filter '*.ps1' -ErrorAction SilentlyContinue
    foreach ($Item in $ActionFiles) {

        $Action = Read-TMActionScriptFile -Path $Item.FullName

        ## Add an Artifact to the inventory
        [void]$Inventory.Actions.Add($Action)

        ## Add a property for this Field in the Relationships data
        # $Inventory.Relationships.Actions.($Action.name) = @{
        # Provider = $Action.provider.name
        # Fields = [System.Collections.ArrayList]@()
        # Recipes = [System.Collections.ArrayList]@()
        # RecipeTaskSpecs = [System.Collections.ArrayList]@()
        # }

        # ## Add this Action to the Provider's list as well
        # [void]($Inventory.Relationships.Providers.($Action.provider.name).Actions.Add($Action.Name))
    }

    ## Collect Data Scripts
    $DataScriptFiles = Get-ChildItem -Path "$Path\DataScripts" -Recurse -Filter '*.groovy' -ErrorAction SilentlyContinue
    foreach ($Item in $DataScriptFiles) {

        $DataScript = Read-TMDatascriptFile -Path $Item.FullName

        ## Add an Artifact to the inventory
        [void]$Inventory.DataScripts.Add($DataScript)

        ## Add a property for this Field in the Relationships data
        # $Inventory.Relationships.DataScripts.($DataScript.name) = @{
        # Provider = $ActioDatascript.provider.name
        # Fields = [System.Collections.ArrayList]@()
        # }

        # ## Add this Datascript to the Provider's list as well
        # [void]($Inventory.Relationships.Providers.($DataScript.provider.name).Datascripts.Add($DataScript.Name))
    }

    ## Create a flat inventory of Artifacts


    # Send the package back if Passthru was specified
    if (-not ([String]::IsNullOrWhiteSpace($OutPath))) {
        $Inventory | ConvertTo-Json -Depth 100 | Set-Content -Path $OutPath -Force
    }

    # Send the package back if Passthru was specified
    if ($Passthru) {
        $Inventory
    }
}