AutomatedLabDefinition.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
#region Internals
$unattendedXmlDefaultContent2012 = @'
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
  <settings pass="generalize">
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <DoNotCleanTaskBar>true</DoNotCleanTaskBar>
    </component>
    <component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <SkipRearm>1</SkipRearm>
    </component>
  </settings>
  <settings pass="specialize">
    <component name="Microsoft-Windows-UnattendedJoin" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
      <Identification>
        <JoinWorkgroup >NET</JoinWorkgroup>
      </Identification>
    </component>
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
      <ComputerName>SERVER</ComputerName>
      <RegisteredOrganization>vm.net</RegisteredOrganization>
      <RegisteredOwner>NA</RegisteredOwner>
      <DoNotCleanTaskBar>true</DoNotCleanTaskBar>
      <TimeZone>UTC</TimeZone>
    </component>
    <component name="Microsoft-Windows-IE-InternetExplorer" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Home_Page>about:blank</Home_Page>
      <DisableFirstRunWizard>true</DisableFirstRunWizard>
      <DisableOOBAccelerators>true</DisableOOBAccelerators>
      <DisableDevTools>true</DisableDevTools>
      <LocalIntranetSites></LocalIntranetSites>
      <TrustedSites></TrustedSites>
    </component>
    <component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
      <UserAuthentication>0</UserAuthentication>
    </component>
    <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <RunSynchronous>
        <RunSynchronousCommand wcm:action="add">
          <Description>EnableAdmin</Description>
          <Order>1</Order>
          <Path>cmd /c net user Administrator /active:yes</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
          <Description>UnfilterAdministratorToken</Description>
          <Order>2</Order>
          <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v FilterAdministratorToken /t REG_DWORD /d 0 /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
          <Description>Remove First Logon Animation</Description>
          <Order>3</Order>
          <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v EnableFirstLogonAnimation /d 0 /t REG_DWORD /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
          <Description>Do Not Open Server Manager At Logon</Description>
          <Order>4</Order>
          <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\ServerManager" /v "DoNotOpenServerManagerAtLogon" /d 1 /t REG_DWORD /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Do not Open Initial Configuration Tasks At Logon</Description>
            <Order>5</Order>
            <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\ServerManager\oobe" /v "DoNotOpenInitialConfigurationTasksAtLogon" /d 1 /t REG_DWORD /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Set Power Scheme to High Performance</Description>
            <Order>6</Order>
            <Path>cmd /c powercfg -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Don't require password when console wakes up</Description>
            <Order>7</Order>
            <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c fea3413e-7e05-4911-9a71-700331f1c294 0e796bdb-100d-47d6-a2d5-f7d2daa51f51 0</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Sleep timeout</Description>
            <Order>8</Order>
            <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>monitor timeout</Description>
            <Order>9</Order>
            <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Enable PowerShell Remoting 1</Description>
            <Order>10</Order>
            <Path>cmd /c winrm quickconfig -quiet</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Enable PowerShell Remoting 2</Description>
            <Order>11</Order>
            <Path>cmd /c winrm quickconfig -quiet -force</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Enable PowerShell Remoting 3</Description>
            <Order>12</Order>
            <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell /v ExecutionPolicy /t REG_SZ /d Unrestricted /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Disable UAC</Description>
            <Order>13</Order>
            <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system /v EnableLUA /t REG_DWORD /d 0 /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Configure BgInfo to start automatically</Description>
            <Order>14</Order>
            <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v BgInfo /t REG_SZ /d "C:\Windows\BgInfo.exe C:\Windows\BgInfo.bgi /Timer:0 /nolicprompt" /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Enable Remote Desktop firewall rules</Description>
            <Order>15</Order>
            <Path>cmd /c netsh advfirewall Firewall set rule group="Remote Desktop" new enable=yes</Path>
        </RunSynchronousCommand>
      </RunSynchronous>
    </component>
    <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <InputLocale>0409:00000409</InputLocale>
      <SystemLocale>EN-US</SystemLocale>
      <UILanguage>EN-US</UILanguage>
      <UserLocale>EN-US</UserLocale>
    </component>
    <component name="Microsoft-Windows-TapiSetup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <TapiConfigured>0</TapiConfigured>
      <TapiUnattendLocation>
        <AreaCode>""</AreaCode>
        <CountryOrRegion>1</CountryOrRegion>
        <LongDistanceAccess>9</LongDistanceAccess>
        <OutsideAccess>9</OutsideAccess>
        <PulseOrToneDialing>1</PulseOrToneDialing>
        <DisableCallWaiting>""</DisableCallWaiting>
        <InternationalCarrierCode>""</InternationalCarrierCode>
        <LongDistanceCarrierCode>""</LongDistanceCarrierCode>
        <Name>Default</Name>
      </TapiUnattendLocation>
    </component>
    <component name="Microsoft-Windows-IE-ESC" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <IEHardenAdmin>false</IEHardenAdmin>
      <IEHardenUser>false</IEHardenUser>
    </component>
    <component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <fDenyTSConnections>false</fDenyTSConnections>
    </component>
    <component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    <component name="Microsoft-Windows-TCPIP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    <component name="Microsoft-Windows-DNS-Client" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    <component name="Microsoft-Windows-NetBT" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </settings>
  <settings pass="oobeSystem">
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
      <FirstLogonCommands>
        <SynchronousCommand wcm:action="add">
            <CommandLine>winrm quickconfig -quiet</CommandLine>
            <Description>Enable Windows Remoting</Description>
            <Order>1</Order>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <CommandLine>winrm quickconfig -quiet -force</CommandLine>
            <Description>Enable Windows Remoting</Description>
            <Order>2</Order>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <CommandLine>winrm set winrm/config/service/auth @{CredSSP="true"}</CommandLine>
            <Description>Enable Windows Remoting CredSSP</Description>
            <Order>3</Order>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <Description>Bring all additional disks online</Description>
            <Order>4</Order>
            <CommandLine>PowerShell -File C:\AdditionalDisksOnline.ps1</CommandLine>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <Description>Disable .net Optimization</Description>
            <Order>5</Order>
            <CommandLine>PowerShell -Command "schtasks.exe /query /FO CSV | ConvertFrom-Csv | Where-Object { $_.TaskName -like '*NGEN*' } | ForEach-Object { schtasks.exe /Change /TN $_.TaskName /Disable }"</CommandLine>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <Description>Configure WinRM settings</Description>
            <Order>6</Order>
            <CommandLine>PowerShell -File C:\WinRmCustomization.ps1</CommandLine>
        </SynchronousCommand>
      </FirstLogonCommands>
      <UserAccounts>
        <AdministratorPassword>
          <Value>Password1</Value>
          <PlainText>true</PlainText>
        </AdministratorPassword>
        <LocalAccounts>
          <LocalAccount wcm:action="add">
            <Password>
              <Value>Password1</Value>
              <PlainText>true</PlainText>
            </Password>
            <Group>Administrators</Group>
            <DisplayName>AL</DisplayName>
            <Name>AL</Name>
          </LocalAccount>
        </LocalAccounts>
      </UserAccounts>
      <OOBE>
        <HideEULAPage>true</HideEULAPage>
        <ProtectYourPC>3</ProtectYourPC>
        <HideOnlineAccountScreens>true</HideOnlineAccountScreens>
        <HideLocalAccountScreen>true</HideLocalAccountScreen>
        <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
      </OOBE>
      <RegisteredOrganization>vm.net</RegisteredOrganization>
      <RegisteredOwner>NA</RegisteredOwner>
    </component>
    <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <InputLocale>0409:00000409</InputLocale>
      <SystemLocale>En-US</SystemLocale>
      <UILanguage>EN-US</UILanguage>
      <UserLocale>EN-Us</UserLocale>
    </component>
  </settings>
</unattend>
'@


$unattendedXmlDefaultContent2008 = @'
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
  <settings pass="generalize">
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <DoNotCleanTaskBar>true</DoNotCleanTaskBar>
    </component>
    <component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <SkipRearm>1</SkipRearm>
    </component>
  </settings>
  <settings pass="specialize">
    <component name="Microsoft-Windows-UnattendedJoin" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
      <Identification>
        <JoinWorkgroup >NET</JoinWorkgroup>
      </Identification>
    </component>
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
      <ComputerName>SERVER</ComputerName>
      <RegisteredOrganization>vm.net</RegisteredOrganization>
      <RegisteredOwner>NA</RegisteredOwner>
      <DoNotCleanTaskBar>true</DoNotCleanTaskBar>
      <TimeZone>UTC</TimeZone>
    </component>
    <component name="Microsoft-Windows-IE-InternetExplorer" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Home_Page>about:blank</Home_Page>
      <DisableFirstRunWizard>true</DisableFirstRunWizard>
      <DisableOOBAccelerators>true</DisableOOBAccelerators>
      <DisableDevTools>true</DisableDevTools>
      <LocalIntranetSites>http://*.vm.net;https://*.vm.net</LocalIntranetSites>
      <TrustedSites>https://*.vm.net</TrustedSites>
    </component>
    <component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
      <UserAuthentication>0</UserAuthentication>
    </component>
    <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <RunSynchronous>
        <RunSynchronousCommand wcm:action="add">
            <Description>Disable and stop Windows Firewall 1</Description>
            <Order>1</Order>
            <Path>cmd /c sc config MpsSvc start=disabled</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Disable and stop Windows Firewall 2</Description>
            <Order>2</Order>
            <Path>cmd /c sc stop MpsSvc</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>EnableAdmin</Description>
            <Order>3</Order>
            <Path>cmd /c net user Administrator /active:yes</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>UnfilterAdministratorToken</Description>
            <Order>4</Order>
            <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v FilterAdministratorToken /t REG_DWORD /d 0 /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Remove First Logon Animation</Description>
            <Order>5</Order>
            <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v EnableFirstLogonAnimation /d 0 /t REG_DWORD /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Do Not Open Server Manager At Logon</Description>
            <Order>6</Order>
            <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\ServerManager" /v "DoNotOpenServerManagerAtLogon" /d 1 /t REG_DWORD /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Do not Open Initial Configuration Tasks At Logon</Description>
            <Order>7</Order>
            <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\ServerManager\oobe" /v "DoNotOpenInitialConfigurationTasksAtLogon" /d 1 /t REG_DWORD /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Set Power Scheme to High Performance</Description>
            <Order>8</Order>
            <Path>cmd /c powercfg -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Don't require password when console wakes up</Description>
            <Order>9</Order>
            <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c fea3413e-7e05-4911-9a71-700331f1c294 0e796bdb-100d-47d6-a2d5-f7d2daa51f51 0</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Sleep timeout</Description>
            <Order>10</Order>
            <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>monitor timeout</Description>
            <Order>11</Order>
            <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Enable PowerShell Remoting 1</Description>
            <Order>12</Order>
            <Path>cmd /c winrm quickconfig -quiet</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Enable PowerShell Remoting 2</Description>
            <Order>13</Order>
            <Path>cmd /c winrm quickconfig -quiet -force</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Enable PowerShell Remoting 2</Description>
            <Order>14</Order>
            <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell /v ExecutionPolicy /t REG_SZ /d Unrestricted /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Disable UAC</Description>
            <Order>15</Order>
            <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system /v EnableLUA /t REG_DWORD /d 0 /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Configure BgInfo to start automatically</Description>
            <Order>16</Order>
            <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v BgInfo /t REG_SZ /d "C:\Windows\BgInfo.exe C:\Windows\BgInfo.bgi /Timer:0 /nolicprompt" /f</Path>
        </RunSynchronousCommand>
        <RunSynchronousCommand wcm:action="add">
            <Description>Enable Remote Desktop firewall rules</Description>
            <Order>17</Order>
            <Path>cmd /c netsh advfirewall Firewall set rule group="Remote Desktop" new enable=yes</Path>
        </RunSynchronousCommand>
      </RunSynchronous>
    </component>
    <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <InputLocale>0409:00000409</InputLocale>
      <SystemLocale>EN-US</SystemLocale>
      <UILanguage>EN-US</UILanguage>
      <UserLocale>EN-US</UserLocale>
    </component>
    <component name="Microsoft-Windows-TapiSetup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <TapiConfigured>0</TapiConfigured>
      <TapiUnattendLocation>
        <AreaCode>""</AreaCode>
        <CountryOrRegion>1</CountryOrRegion>
        <LongDistanceAccess>9</LongDistanceAccess>
        <OutsideAccess>9</OutsideAccess>
        <PulseOrToneDialing>1</PulseOrToneDialing>
        <DisableCallWaiting>""</DisableCallWaiting>
        <InternationalCarrierCode>""</InternationalCarrierCode>
        <LongDistanceCarrierCode>""</LongDistanceCarrierCode>
        <Name>Default</Name>
      </TapiUnattendLocation>
    </component>
    <component name="Microsoft-Windows-IE-ESC" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <IEHardenAdmin>false</IEHardenAdmin>
      <IEHardenUser>false</IEHardenUser>
    </component>
    <component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <fDenyTSConnections>false</fDenyTSConnections>
    </component>
    <component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    <component name="Microsoft-Windows-TCPIP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    <component name="Microsoft-Windows-DNS-Client" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    <component name="Microsoft-Windows-NetBT" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </settings>
  <settings pass="oobeSystem">
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
      <FirstLogonCommands>
      <SynchronousCommand wcm:action="add">
            <CommandLine>cmd /c sc config MpsSvc start=disabled</CommandLine>
            <Description>1</Description>
            <Order>1</Order>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <CommandLine>cmd /c sc stop MpsSvc</CommandLine>
            <Description>2</Description>
            <Order>2</Order>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <CommandLine>winrm quickconfig -quiet</CommandLine>
            <Description>Enable Windows Remoting</Description>
            <Order>3</Order>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <CommandLine>winrm quickconfig -quiet -force</CommandLine>
            <Description>Enable Windows Remoting</Description>
            <Order>4</Order>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <CommandLine>winrm set winrm/config/service/auth @{CredSSP="true"}</CommandLine>
            <Description>Enable Windows Remoting CredSSP</Description>
            <Order>5</Order>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <Description>Bring all additional disks online</Description>
            <Order>6</Order>
            <CommandLine>PowerShell -File C:\AdditionalDisksOnline.ps1</CommandLine>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <Description>Disable .net Optimization</Description>
            <Order>7</Order>
            <CommandLine>PowerShell -Command "schtasks.exe /query /FO CSV | ConvertFrom-Csv | Where-Object { $_.TaskName -like '*NGEN*' } | ForEach-Object { schtasks.exe /Change /TN $_.TaskName /Disable }"</CommandLine>
        </SynchronousCommand>
        <SynchronousCommand wcm:action="add">
            <Description>Configure WinRM settings</Description>
            <Order>8</Order>
            <CommandLine>PowerShell -File C:\WinRmCustomization.ps1</CommandLine>
        </SynchronousCommand>
      </FirstLogonCommands>
      <UserAccounts>
        <AdministratorPassword>
          <Value>Password1</Value>
          <PlainText>true</PlainText>
        </AdministratorPassword>
        <LocalAccounts>
          <LocalAccount wcm:action="add">
            <Password>
              <Value>Password1</Value>
              <PlainText>true</PlainText>
            </Password>
            <Group>Administrators</Group>
            <DisplayName>AL</DisplayName>
            <Name>AL</Name>
          </LocalAccount>
        </LocalAccounts>
      </UserAccounts>
      <OOBE>
        <HideEULAPage>true</HideEULAPage>
        <NetworkLocation>Work</NetworkLocation>
        <ProtectYourPC>3</ProtectYourPC>
      </OOBE>
      <RegisteredOrganization>vm.net</RegisteredOrganization>
      <RegisteredOwner>NA</RegisteredOwner>
    </component>
    <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <InputLocale>0409:00000409</InputLocale>
      <SystemLocale>En-US</SystemLocale>
      <UILanguage>EN-US</UILanguage>
      <UserLocale>EN-Us</UserLocale>
    </component>
  </settings>
</unattend>
'@


$kickstartContent = @"
install
cdrom
text --non-interactive
firstboot --disable
reboot
eula --agreed
bootloader --append="biosdevname=0 net.ifnames=0"
zerombr
clearpart --all
autopart
"@


$autoyastContent = @"
<?xml version="1.0"?>
<!DOCTYPE profile>
<profile
  xmlns="http://www.suse.com/1.0/yast2ns"
  xmlns:config="http://www.suse.com/1.0/configns">
  <general>
  <signature-handling>
    <accept_unsigned_file config:type="boolean">true</accept_unsigned_file>
    <accept_file_without_checksum config:type="boolean">true</accept_file_without_checksum>
    <accept_verification_failed config:type="boolean">true</accept_verification_failed>
    <accept_unknown_gpg_key config:type="boolean">true</accept_unknown_gpg_key>
    <import_gpg_key config:type="boolean">true</import_gpg_key>
    <accept_non_trusted_gpg_key config:type="boolean">true</accept_non_trusted_gpg_key>
    </signature-handling>
    <self_update config:type="boolean">false</self_update>
  <mode>
    <halt config:type="boolean">false</halt>
    <forceboot config:type="boolean">false</forceboot>
    <final_reboot config:type="boolean">true</final_reboot>
    <final_halt config:type="boolean">false</final_halt>
    <confirm_base_product_license config:type="boolean">false</confirm_base_product_license>
    <confirm config:type="boolean">false</confirm>
    <second_stage config:type="boolean">true</second_stage>
  </mode>
  </general>
  <partitioning config:type="list">
    <drive>
        <disklabel>gpt</disklabel>
        <device>/dev/sda</device>
        <use>free</use>
        <partitions config:type="list">
            <partition>
                <filesystem config:type="symbol">vfat</filesystem>
                <mount>/boot</mount>
                <size>1G</size>
            </partition>
            <partition>
                <filesystem config:type="symbol">vfat</filesystem>
                <mount>/boot/efi</mount>
                <size>1G</size>
            </partition>
            <partition>
                <filesystem config:type="symbol">swap</filesystem>
                <mount>/swap</mount>
                <size>auto</size>
            </partition>
            <partition>
                <filesystem config:type="symbol">ext4</filesystem>
                <mount>/</mount>
                <size>auto</size>
            </partition>
        </partitions>
    </drive>
</partitioning>
<bootloader>
  <loader_type>grub2-efi</loader_type>
  <global>
    <activate config:type="boolean">true</activate>
    <boot_boot>true</boot_boot>
  </global>
 </bootloader>
<language>
    <language>en_US</language>
</language>
<timezone>
<!-- https://raw.githubusercontent.com/yast/yast-country/master/timezone/src/data/timezone_raw.ycp -->
    <hwclock>UTC</hwclock>
    <timezone>ETC/GMT</timezone>
</timezone>
<keyboard>
<!-- https://raw.githubusercontent.com/yast/yast-country/master/keyboard/src/data/keyboard_raw.ycp -->
    <keymap>english-us</keymap>
</keyboard>
<software>
    <patterns config:type="list">
    <pattern>base</pattern>
    <pattern>enhanced_base</pattern>
  </patterns>
  <install_recommended config:type="boolean">true</install_recommended>
  <packages config:type="list">
    <package>iputils</package>
    <package>vim</package>
    <package>less</package>
  </packages>
</software>
<services-manager>
  <default_target>multi-user</default_target>
  <services>
    <enable config:type="list">
      <service>sshd</service>
    </enable>
  </services>
</services-manager>
<networking>
<interfaces config:type="list">
</interfaces>
<net-udev config:type="list">
</net-udev>
<dns>
    <nameservers config:type="list">
    </nameservers>
</dns>
<routing>
<routes config:type="list">
</routes>
</routing>
</networking>
<users config:type="list">
  <user>
    <username>root</username>
    <user_password>Password1</user_password>
    <encrypted config:type="boolean">false</encrypted>
  </user>
  </users>
<firewall>
  <enable_firewall config:type="boolean">true</enable_firewall>
  <start_firewall config:type="boolean">true</start_firewall>
</firewall>
<scripts>
    <init-scripts config:type="list">
      <script>
        <source>
        <![CDATA[
            rpm --import https://packages.microsoft.com/keys/microsoft.asc
            rpm -Uvh https://packages.microsoft.com/config/sles/12/packages-microsoft-prod.rpm
            zypper update
            zypper -f -v install powershell omi openssl
            systemctl enable omid
            echo "Subsystem powershell /usr/bin/pwsh -sshs -NoLogo" >> /etc/ssh/sshd_config
            systemctl restart sshd
        ]]>
        </source>
      </script>
    </init-scripts>
  </scripts>
</profile>
"@


#region Get-LabVolumesOnPhysicalDisks

function Get-LabVolumesOnPhysicalDisks
{
    [CmdletBinding()]

    $physicalDisks = Get-PhysicalDisk
    $disks = Get-CimInstance -Class Win32_DiskDrive

    $labVolumes = foreach ($disk in $disks)
    {
        $query = 'ASSOCIATORS OF {{Win32_DiskDrive.DeviceID="{0}"}} WHERE AssocClass=Win32_DiskDriveToDiskPartition' -f $disk.DeviceID.Replace('\', '\\')

        $partitions = Get-CimInstance -Query $query
        foreach ($partition in $partitions)
        {
            $query = 'ASSOCIATORS OF {{Win32_DiskPartition.DeviceID="{0}"}} WHERE AssocClass=Win32_LogicalDiskToPartition' -f $partition.DeviceID
            $volumes = Get-CimInstance -Query $query

            foreach ($volume in $volumes)
            {
                Get-Volume -DriveLetter $volume.DeviceId[0] |
                Add-Member -Name Serial -MemberType NoteProperty -Value $disk.SerialNumber -PassThru |
                Add-Member -Name Signature -MemberType NoteProperty -Value $disk.Signature -PassThru
            }
        }
    }

    $labVolumes |
    Select-Object -ExpandProperty DriveLetter |
    Sort-Object |
    ForEach-Object {
        $localDisk = New-Object AutomatedLab.LocalDisk($_)
        $localDisk.Serial = $_.Serial
        $localDisk.Signature = $_.Signature
        $localDisk
    }
}
#endregion Get-LabVolumesOnPhysicalDisks

#region Get-LabFreeDiskSpace
function Get-LabFreeDiskSpace
{
    param(
        [Parameter(Mandatory)]
        [string]$Path
    )

    [uint64]$freeBytesAvailable = 0
    [uint64]$totalNumberOfBytes = 0
    [uint64]$totalNumberOfFreeBytes = 0

    $success = [AutomatedLab.DiskSpaceWin32]::GetDiskFreeSpaceEx($Path, [ref]$freeBytesAvailable, [ref]$totalNumberOfBytes, [ref]$totalNumberOfFreeBytes)
    if (-not $success)
    {
        Write-Error "Could not determine free disk space of path '$Path'"
    }

    New-Object -TypeName PSObject -Property @{
        TotalNumberOfBytes     = $totalNumberOfBytes
        FreeBytesAvailable     = $freeBytesAvailable
        TotalNumberOfFreeBytes = $totalNumberOfFreeBytes
    }
}
#endregion Internals

#region Lab Definition Functions
#region New-LabDefinition
function New-LabDefinition
{
    [CmdletBinding()]
    param (
        [string]$Name,

        [string]$VmPath = (Get-LabConfigurationItem -Name VmPath),

        [int]$ReferenceDiskSizeInGB = 50,

        [long]$MaxMemory = 0,

        [hashtable]$Notes,

        [switch]$UseAllMemory = $false,

        [switch]$UseStaticMemory = $false,

        [ValidateSet('Azure', 'HyperV', 'VMWare')]
        [string]$DefaultVirtualizationEngine,

        [switch]$Passthru
    )

    Write-LogFunctionEntry
    $global:PSLog_Indent = 0

    $hostOSVersion = ([Environment]::OSVersion).Version
    if (-Not $IsLinux -and (($hostOSVersion -lt [System.Version]'6.2') -or (($hostOSVersion -ge [System.Version]'6.4') -and ($hostOSVersion.Build -lt '14393'))))
    {
        $osName = $(([Environment]::OSVersion).VersionString.PadRight(10))
        $osBuild = $(([Environment]::OSVersion).Version.ToString().PadRight(11))
        Write-PSFMessage -Level Host '***************************************************************************'
        Write-PSFMessage -Level Host ' THIS HOST MACHINE IS NOT RUNNING AN OS SUPPORTED BY AUTOMATEDLAB!'
        Write-PSFMessage -Level Host ''
        Write-PSFMessage -Level Host ' Operating System detected as:'
        Write-PSFMessage -Level Host " Name: $osName"
        Write-PSFMessage -Level Host " Build: $osBuild"
        Write-PSFMessage -Level Host ''
        Write-PSFMessage -Level Host ' AutomatedLab is supported on the following virtualization platforms'
        Write-PSFMessage -Level Host ''
        Write-PSFMessage -Level Host ' - Microsoft Azure'
        Write-PSFMessage -Level Host ' - Windows 2016 1607 or newer'
        Write-PSFMessage -Level Host ' - Windows 10 1607 or newer'
        Write-PSFMessage -Level Host ' - Windows 8.1 Professional or Enterprise'
        Write-PSFMessage -Level Host ' - Windows 2012 R2'

        Write-PSFMessage -Level Host '***************************************************************************'
    }

    if ($DefaultVirtualizationEngine -eq 'Azure')
    {
        $null = Test-LabAzureModuleAvailability -ErrorAction Stop
    }

    #settings for a new log

    #reset the log and its format
    $Global:AL_DeploymentStart = $null
    $Global:taskStart = @()
    $Global:indent = 0
    $global:AL_CurrentLab = $null

    $Global:labDeploymentNoNewLine = $false

    $Script:reservedAddressSpaces = $null

    Write-ScreenInfo -Message 'Initialization' -TimeDelta ([timespan]0) -TimeDelta2 ([timespan]0) -TaskStart

    $hostOsName = if (($IsLinux -or $IsMacOs) -and (Get-Command -Name lsb_release -ErrorAction SilentlyContinue)) 
    {
        lsb_release -d -s
    }
    elseif (-not ($IsLinux -or $IsMacOs)) # easier than IsWindows, which does not exist in Windows PowerShell...
    {
        (Get-CimInstance -ClassName Win32_OperatingSystem).Caption
    }
    else
    {
        'Unknown'
    }

    Write-ScreenInfo -Message "Host operating system version: '$hostOsName, $($hostOSVersion.ToString())'"

    if (-not $Name)
    {
        $reservedMacAddresses = @()

        #Microsoft
        $reservedMacAddresses += '00:03:FF'
        $reservedMacAddresses += '00:0D:3A'
        $reservedMacAddresses += '00:12:5A'
        $reservedMacAddresses += '00:15:5D'
        $reservedMacAddresses += '00:17:FA'
        $reservedMacAddresses += '00:50:F2'
        $reservedMacAddresses += '00:1D:D8'

        #VMware
        $reservedMacAddresses += '00:05:69'
        $reservedMacAddresses += '00:0C:29'
        $reservedMacAddresses += '00:1C:14'
        $reservedMacAddresses += '00:50:56'

        #Citrix
        $reservedMacAddresses += '00:16:3E'

        $macAddress = Get-OnlineAdapterHardwareAddress |
        Where-Object { $_.SubString(0, 8) -notin $reservedMacAddresses } |
        Select-Object -Unique

        $Name = "$($env:COMPUTERNAME)$($macAddress.SubString(12,2))$($macAddress.SubString(15,2))"
        Write-ScreenInfo -Message "Lab name and network name has automatically been generated as '$Name' (if not overridden)"
    }

    Write-ScreenInfo -Message "Creating new lab definition with name '$Name'"

    #remove the current lab from memory
    if (Get-Lab -ErrorAction SilentlyContinue)
    {
        Clear-Lab
    }

    $global:labExported = $false

    $global:firstAzureVMCreated = $false
    $global:existingAzureNetworks = @()

    $global:cacheVMs = $null

    $script:existingHyperVVirtualSwitches = $null

    #cleanup $PSDefaultParameterValues for entries for AL functions
    $automatedLabPSDefaultParameterValues = $global:PSDefaultParameterValues.GetEnumerator() | Where-Object { (Get-Command ($_.Name).Split(':')[0]).Module -like 'Automated*' }
    if ($automatedLabPSDefaultParameterValues)
    {
        foreach ($entry in $automatedLabPSDefaultParameterValues)
        {
            $global:PSDefaultParameterValues.Remove($entry.Name)
            Write-ScreenInfo -Message "Entry '$($entry.Name)' with value '$($entry.Value)' was removed from `$PSDefaultParameterValues. If needed, modify `$PSDefaultParameterValues after calling New-LabDefinition'" -Type Warning
        }
    }

    if (Get-Variable -Name 'autoIPAddress' -Scope Script -ErrorAction SilentlyContinue)
    {
        Remove-Variable -Name 'AutoIPAddress' -Scope Script
    }

    if ($global:labNamePrefix)
    {
        $Name = "$global:labNamePrefix$Name" 
    }

    $script:labPath = "$((Get-LabConfigurationItem -Name LabAppDataRoot))/Labs/$Name"
    Write-ScreenInfo -Message "Location of lab definition files will be '$($script:labpath)'"

    $script:lab = New-Object AutomatedLab.Lab

    $script:lab.Name = $Name

    Update-LabSysinternalsTools

    while (Get-LabVirtualNetworkDefinition)
    {
        Remove-LabVirtualNetworkDefinition -Name (Get-LabVirtualNetworkDefinition)[0].Name
    }

    $machineDefinitionFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem MachineFileName)
    $machineDefinitionFile = New-Object AutomatedLab.MachineDefinitionFile
    $machineDefinitionFile.Path = $machineDefinitionFilePath
    $script:lab.MachineDefinitionFiles.Add($machineDefinitionFile)

    $diskDefinitionFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem DiskFileName)
    $diskDefinitionFile = New-Object AutomatedLab.DiskDefinitionFile
    $diskDefinitionFile.Path = $diskDefinitionFilePath
    $script:lab.DiskDefinitionFiles.Add($diskDefinitionFile)

    $sourcesPath = $labSources
    if (-not $sourcesPath)
    {
        $sourcesPath = New-LabSourcesFolder
    }

    Write-ScreenInfo -Message "Location of LabSources folder is '$sourcesPath'"

    if (-not (Get-LabIsoImageDefinition) -and $DefaultVirtualizationEngine -ne 'Azure')
    {
        if (-not (Get-ChildItem -Path "$(Get-LabSourcesLocation)\ISOs" -Filter *.iso -Recurse))
        {
            Write-ScreenInfo -Message "No ISO files found in $(Get-LabSourcesLocation)\ISOs folder. If using Hyper-V for lab machines, please add ISO files manually using 'Add-LabIsoImageDefinition'" -Type Warning
        }

        Write-ScreenInfo -Message 'Auto-adding ISO files' -TaskStart
        Get-LabAvailableOperatingSystem -Path "$(Get-LabSourcesLocation)\ISOs" | Out-Null #for updating the cache if necessary
        Add-LabIsoImageDefinition -Path "$(Get-LabSourcesLocation)\ISOs"
        Write-ScreenInfo -Message 'Done' -TaskEnd
    }

    if ($DefaultVirtualizationEngine)
    {
        $script:lab.DefaultVirtualizationEngine = $DefaultVirtualizationEngine
    }

    if ($MaxMemory -ne 0)
    {
        $script:lab.MaxMemory = $MaxMemory
    }
    if ($UseAllMemory)
    {
        $script:lab.MaxMemory = 4TB
    }

    $script:lab.UseStaticMemory = $UseStaticMemory

    $script:lab.Sources.UnattendedXml = $script:labPath
    if ($VmPath)
    {
        $Script:lab.target.Path = $vmPath
        Write-ScreenInfo -Message "Path for VMs specified as '$($script:lab.Target.Path)'" -Type Info
    }

    $script:lab.Target.ReferenceDiskSizeInGB = $ReferenceDiskSizeInGB

    $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Machine
    $script:machines = New-Object $type
    $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Disk
    $script:disks = New-Object $type

    $script:lab.Notes = $Notes

    if ($Passthru)
    {
        $script:lab
    }

    $global:AL_CurrentLab = $script:lab

    Register-LabArgumentCompleters

    Write-LogFunctionExit
}
#endregion New-LabDefinition

#region Get-LabDefinition
function Get-LabDefinition
{
    [CmdletBinding()]
    [OutputType([AutomatedLab.Lab])]
    param ()

    Write-LogFunctionEntry

    return $script:lab

    Write-LogFunctionExit
}
#endregion Get-LabDefinition

#region Set-LabDefinition
function Set-LabDefinition
{
    param
    (
        [AutomatedLab.Lab]
        $Lab,

        [AutomatedLab.Machine[]]
        $Machines,

        [AutomatedLab.Disk[]]
        $Disks
    )

    if ($Lab)
    {
        $script:lab = $Lab
    }

    if ($Machines)
    {
        if (-not $script:machines)
        {
            $script:machines = New-Object 'AutomatedLab.SerializableList[AutomatedLab.Machine]'
        }

        $script:machines.Clear()
        $Machines | ForEach-Object { $script:Machines.Add($_) }
    }

    if ($Disks)
    {
        $script:Disks.Clear()
        $Disks | ForEach-Object { $script:Disks.Add($_) }
    }
}
#endregion

#region Export-LabDefinition
function Export-LabDefinition
{
    [CmdletBinding()]
    param (
        [switch]
        $Force,

        [switch]
        $ExportDefaultUnattendedXml = $true,

        [switch]
        $Silent
    )

    Write-LogFunctionEntry

    if (Get-LabMachineDefinition | Where-Object HostType -eq 'HyperV')
    {
        $osesCount = (Get-LabAvailableOperatingSystem -NoDisplay).Count
    }

    #Automatic DNS configuration in Azure if no DNS server is specified and an AD is being deployed
    foreach ($network in (Get-LabVirtualNetworkDefinition))
    {
        if ($network.HostType -eq 'Azure' -and (Get-LabMachineDefinition -Role RootDC))
        {
            $rootDCs = Get-LabMachineDefinition -Role RootDC
            $dnsServerIP = ''
            if ($rootDCs | Where-Object Network -eq $network)
            {
                $dnsServerIP = ($rootDCs)[0].IpV4Address
            }
            elseif ($rootDCs | Where-Object Network -eq $network)
            {
                $dnsServerIP = ($rootDCs | Where-Object Network -eq $network)[0].IpV4Address
            }
            if (-not ((Get-LabVirtualNetworkDefinition)[0].DnsServers) -and $dnsServerIP)
            {
                (Get-LabVirtualNetworkDefinition)[0].DnsServers = $dnsServerIP
                $dnsServerName = (Get-LabMachineDefinition | Where-Object { $_.IpV4Address -eq $dnsServerIP }).Name

                if (-not $Silent)
                {
                    Write-ScreenInfo -Message "No DNS server was defined for Azure virtual network while AD is being deployed. Setting DNS server to IP address of '$dnsServerName'" -Type Warning
                }
            }
        }
    }

    #Automatic DNS (client) configuration of machines
    $firstRootDc = Get-LabMachineDefinition -Role RootDC | Select-Object -First 1
    $firstRouter = Get-LabMachineDefinition -Role Routing | Select-Object -First 1
    $firstRouterExternalSwitch = $firstRouter.NetworkAdapters | Where-Object { $_.VirtualSwitch.SwitchType -eq 'External' }

    if ($firstRootDc -or $firstRouter)
    {
        foreach ($machine in (Get-LabMachineDefinition))
        {
            if ($firstRouter)
            {
                $mappingNetworks = Compare-Object -ReferenceObject $firstRouter.NetworkAdapters.VirtualSwitch.Name `
                    -DifferenceObject $machine.NetworkAdapters.VirtualSwitch.Name -ExcludeDifferent -IncludeEqual
            }

            foreach ($networkAdapter in $machine.NetworkAdapters)
            {
                if ($networkAdapter.IPv4DnsServers -contains '0.0.0.0')
                {
                    if (-not $machine.IsDomainJoined) #machine is not domain joined, the 1st network adapter's IP of the 1st root DC is used as DNS server
                    {
                        if ($firstRootDc)
                        {
                            $networkAdapter.IPv4DnsServers = $firstRootDc.NetworkAdapters[0].Ipv4Address[0].IpAddress
                        }
                        elseif ($firstRouter)
                        {
                            if ($networkAdapter.VirtualSwitch.Name -in $mappingNetworks.InputObject)
                            {
                                $networkAdapter.IPv4DnsServers = ($firstRouter.NetworkAdapters | Where-Object { $_.VirtualSwitch.Name -eq $networkAdapter.VirtualSwitch.Name }).Ipv4Address.IpAddress
                            }
                        }

                    }
                    elseif ($machine.Roles.Name -contains 'RootDC') #if the machine is RootDC, its 1st network adapter's IP is used for DNS
                    {
                        $networkAdapter.IPv4DnsServers = $machine.NetworkAdapters[0].Ipv4Address[0].IpAddress
                    }
                    elseif ($machine.Roles.Name -contains 'FirstChildDC') #if it is a FirstChildDc, the 1st network adapter's IP of the corresponsing RootDC is used
                    {
                        $firstChildDcRole = $machine.Roles | Where-Object Name -eq 'FirstChildDC'
                        $roleParentDomain = $firstChildDcRole.Properties.ParentDomain
                        $rootDc = Get-LabMachineDefinition -Role RootDC | Where-Object DomainName -eq $roleParentDomain

                        $networkAdapter.IPv4DnsServers = $machine.NetworkAdapters[0].Ipv4Address[0].IpAddress, $rootDc.NetworkAdapters[0].Ipv4Address[0].IpAddress
                    }
                    elseif ($machine.Roles.Name -contains 'DC')
                    {
                        $parentDc = Get-LabMachineDefinition -Role RootDC,FirstChildDc | Where-Object DomainName -eq $machine.DomainName | Select-Object -First 1

                        $networkAdapter.IPv4DnsServers = $machine.NetworkAdapters[0].Ipv4Address[0].IpAddress, $parentDc.NetworkAdapters[0].Ipv4Address[0].IpAddress
                    }
                    else #machine is domain joined and not a RootDC or FirstChildDC
                    {
                        Write-PSFMessage "Looking for a root DC in the machine's domain '$($machine.DomainName)'"
                        $rootDc = Get-LabMachineDefinition -Role RootDC | Where-Object DomainName -eq $machine.DomainName
                        if ($rootDc)
                        {
                            Write-PSFMessage "RootDC found, using the IP address of '$rootDc' for DNS: "
                            $networkAdapter.IPv4DnsServers = $rootDc.NetworkAdapters[0].Ipv4Address[0].IpAddress
                        }
                        else
                        {
                            Write-PSFMessage "No RootDC found, looking for FirstChildDC in the machine's domain"
                            $firstChildDC = Get-LabMachineDefinition -Role FirstChildDC | Where-Object DomainName -eq $machine.DomainName

                            if ($firstChildDC)
                            {
                                $networkAdapter.IPv4DnsServers = $firstChildDC.NetworkAdapters[0].Ipv4Address[0].IpAddress
                            }
                            else
                            {
                                Write-ScreenInfo "Automatic assignment of DNS server did not work for machine '$machine'. No domain controller could be found for domain '$($machine.DomainName)'" -Type Warning
                            }
                        }
                    }
                }

                #if there is a router in the network and no gateways defined, we try to set the gateway automatically. This does not
                #apply to network adapters that have a gateway manually configured or set to DHCP, any network adapter on a router,
                #or if there is there wasn't found an external network adapter on the router ($firstRouterExternalSwitch)
                if ($networkAdapter.Ipv4Gateway.Count -eq 0 -and
                    $firstRouterExternalSwitch -and
                    $machine.Roles.Name -notcontains 'Routing' -and
                    -not $networkAdapter.UseDhcp
                )
                {
                    if ($networkAdapter.VirtualSwitch.Name -in $mappingNetworks.InputObject)
                    {
                        $networkAdapter.Ipv4Gateway.Add(($firstRouter.NetworkAdapters | Where-Object { $_.VirtualSwitch.Name -eq $networkAdapter.VirtualSwitch.Name } | Select-Object -First 1).Ipv4Address.IpAddress)
                    }
                }
            }
        }
    }

    if (Get-LabMachineDefinition | Where-Object HostType -eq HyperV)
    {
        $hypervMachines = Get-LabMachineDefinition | Where-Object { $_.HostType -eq 'HyperV' -and -not $_.SkipDeployment }
        $hypervUsedOperatingSystems = Get-LabAvailableOperatingSystem -NoDisplay | Where-Object OperatingSystemImageName -in $hypervMachines.OperatingSystem.OperatingSystemName

        $spaceNeededBaseDisks = ($hypervUsedOperatingSystems | Measure-Object -Property Size -Sum).Sum
        $spaceBaseDisksAlreadyClaimed = ($hypervUsedOperatingSystems | Measure-Object -Property size -Sum).Sum
        $spaceNeededData = ($hypervMachines | Where-Object { -not (Get-VM -Name $_.ResourceName -ErrorAction SilentlyContinue) }).Count * 2GB

        $spaceNeeded = $spaceNeededBaseDisks + $spaceNeededData - $spaceBaseDisksAlreadyClaimed

        Write-PSFMessage -Message "Space needed by HyperV base disks: $([int]($spaceNeededBaseDisks / 1GB))"
        Write-PSFMessage -Message "Space needed by HyperV base disks but already claimed: $([int]($spaceBaseDisksAlreadyClaimed / 1GB * -1))"
        Write-PSFMessage -Message "Space estimated for HyperV data: $([int]($spaceNeededData / 1GB))"
        if (-not $Silent)
        {
            Write-ScreenInfo -Message "Estimated (additional) local drive space needed for all machines: $([System.Math]::Round(($spaceNeeded / 1GB),2)) GB" -Type Info
        }

        $labTargetPath = (Get-LabDefinition).Target.Path
        if ($labTargetPath)
        {
            if (-not (Test-Path -Path $labTargetPath))
            {
                try
                {
                    Write-PSFMessage "Creating new folder '$labTargetPath'"
                    New-Item -ItemType Directory -Path $labTargetPath -ErrorAction Stop | Out-Null
                }
                catch
                {
                    Write-Error -Message "Could not create folder '$labTargetPath'. Please make sure that the folder is accessibe and you have permission to write."
                    return
                }
            }

            Write-PSFMessage "Calling 'Get-LabFreeDiskSpace' targeting path '$labTargetPath'"
            $freeSpace = (Get-LabFreeDiskSpace -Path $labTargetPath).FreeBytesAvailable
            Write-PSFMessage "Free disk space is '$([Math]::Round($freeSpace / 1GB, 2))GB'"
            if ($freeSpace -lt $spaceNeeded)
            {
                throw "VmPath parameter is specified for the lab and contains: '$labTargetPath'. However, estimated needed space be $([int]($spaceNeeded / 1GB))GB but drive has only $([System.Math]::Round($freeSpace / 1GB)) GB of free space"
            }
        }
        else
        {
            Set-LabLocalVirtualMachineDiskAuto
            $labTargetPath = (Get-LabDefinition).Target.Path
            if (-not $labTargetPath)
            {
                Throw 'No local drive found matching requirements for free space'
            }
        }

        if (-not $Silent)
        {
            Write-ScreenInfo -Message "Location of Hyper-V machines will be '$labTargetPath'"
        }
    }


    $lab.LabFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem LabFileName)
    $script:lab | Add-Member -Name Path -MemberType NoteProperty -Value $labFilePath -Force

    if (-not (Test-Path $script:labPath))
    {
        New-Item -Path $script:labPath -ItemType Directory | Out-Null
    }

    if (Test-Path -Path $lab.LabFilePath)
    {
        if ($Force)
        {
            Remove-Item -Path $lab.LabFilePath
        }
        else
        {
            Write-Error 'The file does already exist' -TargetObject $lab.LabFilePath
            return
        }
    }

    try
    {
        $script:lab.Export($lab.LabFilePath)
    }
    catch
    {
        throw $_
    }

    $machineFilePath = $script:lab.MachineDefinitionFiles[0].Path
    $diskFilePath = $script:lab.DiskDefinitionFiles[0].Path

    if (Test-Path -Path $machineFilePath)
    {
        if ($Force)
        {
            Remove-Item -Path $machineFilePath
        }
        else
        {
            Write-Error 'The file does already exist' -TargetObject $machineFilePath
            return
        }
    }

    $script:machines.Export($machineFilePath)
    $script:disks.Export($diskFilePath)

    if ($ExportDefaultUnattendedXml)
    {
        if ($script:machines.Count -eq 0)
        {
            Write-ScreenInfo 'There are no machines defined, nothing to export' -Type Warning
        }
        else
        {
            if ($Script:machines.OperatingSystem | Where-Object Version -lt '6.2')
            {
                $unattendedXmlDefaultContent2008 | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath Unattended2008.xml) -Encoding unicode
            }
            if ($Script:machines.OperatingSystem | Where-Object Version -ge '6.2')
            {
                $unattendedXmlDefaultContent2012 | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath Unattended2012.xml) -Encoding unicode
            }
            if ($Script:machines | Where-Object LinuxType -eq 'RedHat')
            {
                $kickstartContent | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath ks_default.cfg) -Encoding unicode
            }
            if ($Script:machines | Where-Object LinuxType -eq 'Suse')
            {
                $autoyastContent | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath autoinst_default.xml) -Encoding unicode
            }
        }
    }

    $Global:labExported = $true

    Write-LogFunctionExit
}
#endregion Export-LabDefinition

#region Test-LabDefinition
function Test-LabDefinition
{
    [CmdletBinding()]
    param (
        [string]$Path,

        [switch]$Quiet
    )

    Write-LogFunctionEntry

    $lab = Get-LabDefinition
    if (-not $lab)
    {
        $lab = Get-Lab -ErrorAction SilentlyContinue
    }

    if (-not $lab -and -not $Path)
    {
        Write-Error 'There is no lab loaded and no path specified. Please either import a lab using Import-Lab or point to a lab.xml document using the path parameter'
        return $false
    }

    if (-not $Path)
    {
        $Path = Join-Path -Path $lab.LabPath -ChildPath (Get-LabConfigurationItem LabFileName)
    }

    $labDefinition = Import-LabDefinition -Path $Path -PassThru
    $skipHostFileModification = Get-LabConfigurationItem -Name SkipHostFileModification

    foreach ($machine in (Get-LabMachineDefinition | Where-Object HostType -in 'HyperV', 'VMware' ))
    {
        $hostEntry = Get-HostEntry -HostName $machine

        if ($machine.FriendlyName -or $skipHostFileModification)
        {
                continue #if FriendlyName / ResourceName is defined, host file will not be modified
        }

        if ($hostEntry -and $hostEntry.IpAddress.IPAddressToString -ne $machine.IpV4Address)
        {
            Write-ScreenInfo "There is already an entry for machine '$($machine.Name)' in the hosts file pointing to other IP address(es) ($((Get-HostEntry -HostName $machine).IpAddress.IPAddressToString -join ',')) than the machine '$($machine.Name)' in this lab will have ($($machine.IpV4Address)). Cannot continue."
            $wrongIpInHostEntry = $true
        }
    }
    if ($wrongIpInHostEntry) { return $false }

    #we need to get the machine config files as well
    $machineDefinitionFiles = $labDefinition.MachineDefinitionFiles.Path

    Write-PSFMessage "There are $($machineDefinitionFiles.Count) machine XML file referenced in the lab xml file"
    foreach ($machineDefinitionFile in $machineDefinitionFiles)
    {
        if (-not (Test-Path -Path $machineDefinitionFile))
        {
            throw 'Error importing the machines. Verify the paths in the section <MachineDefinitionFiles> of the lab definition XML file.'
        }
    }

    $Script:ValidationPass = $true

    Write-PSFMessage 'Starting validation against all xml files'
    try
    {
        [AutomatedLab.XmlValidatorArgs]::XmlPath = $Path

        $summaryMessageContainer = New-Object AutomatedLab.ValidationMessageContainer

        $assembly = [System.Reflection.Assembly]::GetAssembly([AutomatedLab.ValidatorBase])

        $validatorCount = 0
        foreach ($t in $assembly.GetTypes())
        {
            if ($t.IsSubclassOf([AutomatedLab.ValidatorBase]))
            {
                try
                {
                    $validator = [AutomatedLab.ValidatorBase][System.Activator]::CreateInstance($t)
                    Write-Debug "Validator '$($validator.MessageContainer.ValidatorName)' took $($validator.Runtime.TotalMilliseconds) milliseconds"

                    $summaryMessageContainer += $validator.MessageContainer
                    $validatorCount++
                }
                catch
                {
                    Write-ScreenInfo "Could not invoke validator $t" -Type Warning
                }
            }
        }

        $summaryMessageContainer.AddSummary()
    }
    catch
    {
        throw $_
    }

    Write-PSFMessage -Message "Lab Validation complete, overvall runtime was $($summaryMessageContainer.Runtime)"

    $messages = $summaryMessageContainer | ForEach-Object { $_.GetFilteredMessages('All') }
    if (-not $Quiet)
    {
        Write-ScreenInfo ($messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Default } | Out-String)

        if ($VerbosePreference -eq 'Continue')
        {
            Write-PSFMessage ($messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::VerboseDebug } | Out-String)
        }
    }
    else
    {
        if ($messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Warning })
        {
            $messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Warning } | ForEach-Object `
            {
                Write-ScreenInfo -Message "Issue: '$($_.TargetObject)'. Cause: $($_.Message)" -Type Warning
            }
        }

        if ($messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Error })
        {
            $messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Error } | ForEach-Object `
            {
                Write-ScreenInfo -Message "Issue: '$($_.TargetObject)'. Cause: $($_.Message)" -Type Error
            }
        }
    }

    if ($messages | Where-Object Type -eq ([AutomatedLab.MessageType]::Error))
    {
        $Script:ValidationPass = $false
        $false
    }
    else
    {
        $Script:ValidationPass = $true
        $true
    }

    Write-LogFunctionExit
}
#endregion Test-LabDefinition
#endregion Lab Definition Functions

#region Domain Definition Functions
#region Add-LabDomainDefinition
function Add-LabDomainDefinition
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Name,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$AdminUser,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$AdminPassword,

        [switch]$PassThru
    )

    Write-LogFunctionEntry

    if ($script:lab.Domains | Where-Object { $_.Name -eq $Name })
    {
        $errorMessage = "A domain with the name '$Name' is already defined"
        Write-Error $errorMessage
        Write-LogFunctionExitWithError -Message $errorMessage
        return
    }

    $domain = New-Object -TypeName AutomatedLab.Domain
    $domain.Name = $Name

    $user = New-Object -TypeName AutomatedLab.User
    $user.UserName = $AdminUser
    $user.Password = $AdminPassword

    $domain.Administrator = $user

    $script:lab.Domains.Add($domain)
    Write-PSFMessage "Added domain '$Name'. Lab now has $($Script:lab.Domains.Count) domain(s) defined"

    if ($PassThru)
    {
        $network
    }

    Write-LogFunctionExit
}
#endregion Add-LabDomainDefinition

#region Get-LabDomainDefinition
function Get-LabDomainDefinition
{
    Write-LogFunctionEntry

    return $script:lab.Domains

    Write-LogFunctionExit
}
#endregion Get-LabDomainDefinition

#region Remove-LabDomainDefinition
function Remove-LabDomainDefinition
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$Name
    )

    Write-LogFunctionEntry

    $domain = $script:lab.Domains | Where-Object { $_.Name -eq $Name }

    if (-not $domain)
    {
        Write-ScreenInfo "There is no domain defined with the name '$Name'" -Type Warning
    }
    else
    {
        [Void]$script:lab.Domains.Remove($domain)
        Write-PSFMessage "Domain '$Name' removed. Lab has $($Script:lab.Domains.Count) domain(s) defined"
    }

    Write-LogFunctionExit
}
#endregion Remove-LabDomainDefinition
#endregion Domain Definition Functions

#region Iso Image Definition Functions
#region Add-LabIsoImageDefinition
function Add-LabIsoImageDefinition
{
    [CmdletBinding()]
    param (

        [string]$Name,

        [string]$Path,

        [Switch]$IsOperatingSystem,

        [switch]$NoDisplay
    )

    Write-LogFunctionEntry

    if ($IsOperatingSystem)
    {
        Write-ScreenInfo -Message 'The -IsOperatingSystem switch parameter is obsolete and thereby ignored' -Type Warning
    }

    if (-not $script:lab)
    {
        throw 'Please create a lab before using this cmdlet. To create a new lab, call New-LabDefinition'
    }

    $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.IsoImage
    #read the cache
    try
    {
        if ($IsLinux -or $IsMacOs) {
            $cachedIsos = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/LocalIsoImages.xml'))
        }
        else
        {
            $cachedIsos = $type::ImportFromRegistry('Cache', 'LocalIsoImages')
        }

        Write-PSFMessage "Read $($cachedIsos.Count) ISO images from the cache"
    }
    catch
    {
        Write-PSFMessage 'Could not read ISO images info from the cache'
        $cachedIsos = New-Object $type
    }

    $lab = try { Get-Lab -ErrorAction Stop } catch { Get-LabDefinition -ErrorAction Stop }
    if ($lab.DefaultVirtualizationEngine -eq 'Azure')
    {
        if (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $Path)
        {
            $isoRoot = 'ISOs'
            if ($Path -notmatch 'ISOs$')
            {
                # Get relative path
                $isoRoot = $Path.Replace($labSources, '')
            }

            if ($isoRoot.StartsWith('\') -or $isoRoot.StartsWith('/') )
            {
                $isoRoot = $isoRoot.Substring(1)
            }

            $isoFiles = Get-LabAzureLabSourcesContent -Path $isoRoot -RegexFilter '\.iso' -File -ErrorAction SilentlyContinue

            if ( -not $IsLinux -and [System.IO.Path]::HasExtension($Path) -or $IsLinux -and $Path -match '\.iso$')
            {
                $isoFiles = $isoFiles | Where-Object {$_.Name -eq (Split-Path -Path $Path -Leaf)}

                if (-not $isoFiles -and $Name)
                {
                    $filterPath = Split-Path -Path $Path -Leaf
                    Write-ScreenInfo -Message "Syncing $filterPath with Azure lab sources storage as it did not exist"
                    Sync-LabAzureLabSources -Filter $filterPath -NoDisplay

                    $isoFiles = Get-LabAzureLabSourcesContent -Path $isoRoot -RegexFilter '\.iso' -File -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq (Split-Path -Path $Path -Leaf)}
                }
            }
        }
    }
    else
    {
        $isoFiles = Get-ChildItem -Path $Path -Filter *.iso -Recurse -ErrorAction SilentlyContinue
    }

    if (-not $isoFiles)
    {
        throw "The specified iso file could not be found or no ISO file could be found in the given folder: $Path"
    }

    $isos = @()
    foreach ($isoFile in $isoFiles)
    {
        if (-not $PSBoundParameters.ContainsKey('Name'))
        {
            $Name = [guid]::NewGuid()
        }
        else
        {
            $cachedIsos.Remove(($cachedIsos | Where-Object Name -eq $name)) | Out-Null
        }

        $iso = New-Object -TypeName AutomatedLab.IsoImage
        $iso.Name = $Name
        $iso.Path = $isoFile.FullName
        $iso.Size = $isoFile.Length

        if ($cachedIsos -contains $iso)
        {
            Write-PSFMessage "The ISO '$($iso.Path)' with a size '$($iso.Size)' is already in the cache."
            $cachedIso = ($cachedIsos -eq $iso)[0]
            if ($PSBoundParameters.ContainsKey('Name'))
            {
                $cachedIso.Name = $Name
            }
            $isos += $cachedIso
        }
        else
        {
            if (-not $script:lab.DefaultVirtualizationEngine -eq 'Azure')
            {
                Write-PSFMessage "The ISO '$($iso.Path)' with a size '$($iso.Size)' is not in the cache. Reading the operating systems from ISO."
                [void] (Mount-DiskImage -ImagePath $isoFile.FullName -StorageType ISO)
                Get-PSDrive | Out-Null #This is just to refresh the drives. Somehow if this cmdlet is not called, PowerShell does not see the new drives.
                $letter = (Get-DiskImage -ImagePath $isoFile.FullName | Get-Volume).DriveLetter
                $isOperatingSystem = (Test-Path "$letter`:\Sources\Install.wim") -or (Test-Path "$letter`:\.discinfo") -or (Test-Path "$letter`:\isolinux") -or (Test-Path "$letter`:\suse")
                [void] (Dismount-DiskImage -ImagePath $isoFile.FullName)
            }

            if ($isOperatingSystem)
            {
                $oses = Get-LabAvailableOperatingSystem -Path $isoFile.FullName
                if ($oses)
                {
                    foreach ($os in $oses)
                    {
                        if ($isos.OperatingSystems -contains $os)
                        {
                            Write-ScreenInfo "The operating system '$($os.OperatingSystemName)' with version '$($os.Version)' is already added to the lab. If this is an issue with cached information, use Clear-LabCache to solve the issue." -Type Warning
                        }
                        $iso.OperatingSystems.Add($os) | Out-Null
                    }
                }
                $cachedIsos.Add($iso) #the new ISO goes into the cache
                $isos += $iso
            }
            else
            {
                $cachedIsos.Add($iso) #ISO is not an OS. Add only if 'Name' is specified. Hence, ISO is manually added
                $isos += $iso
            }
        }
    }

    $duplicateOperatingSystems = $isos | Where-Object { $_.OperatingSystems } |
    Group-Object -Property { "$($_.OperatingSystems.OperatingSystemName) $($_.OperatingSystems.Version)" } |
    Where-Object Count -gt 1

    if ($duplicateOperatingSystems)
    {
        $duplicateOperatingSystems.Group |
        ForEach-Object { $_ } -PipelineVariable iso |
        ForEach-Object { $_.OperatingSystems } |
        ForEach-Object { Write-ScreenInfo "The operating system $($_.OperatingSystemName) version $($_.Version) defined more than once in '$($iso.Path)'" -Type Warning }
    }

    if ($IsLinux -or $IsMacOs)
    {
        $cachedIsos.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/LocalIsoImages.xml'))
    }
    else
    {
        $cachedIsos.ExportToRegistry('Cache', 'LocalIsoImages')
    }

    foreach ($iso in $isos)
    {
        $isosToRemove = $script:lab.Sources.ISOs | Where-Object { $_.Name -eq $iso.Name -or $_.Path -eq $iso.Path }
        foreach ($isoToRemove in $isosToRemove)
        {
            $script:lab.Sources.ISOs.Remove($isoToRemove) | Out-Null
        }

        #$script:lab.Sources.ISOs.Remove($iso) | Out-Null
        $script:lab.Sources.ISOs.Add($iso)
        Write-ScreenInfo -Message "Added '$($iso.Path)'"
    }
    Write-PSFMessage "Final Lab ISO count: $($script:lab.Sources.ISOs.Count)"

    Write-LogFunctionExit
}
#endregion Add-LabIsoImageDefinition

#region Get-LabIsoImageDefinition
function Get-LabIsoImageDefinition
{
    Write-LogFunctionEntry

    $script:lab.Sources.ISOs

    Write-LogFunctionExit
}
#endregion Get-LabIsoImageDefinition

#region Remove-LabIsoImageDefinition
function Remove-LabIsoImageDefinition
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Name
    )

    Write-LogFunctionEntry

    $iso = $script:lab.Sources.ISOs | Where-Object -FilterScript {
        $_.Name -eq $Name
    }

    if (-not $iso)
    {
        Write-ScreenInfo "There is no Iso Image defined with the name '$Name'" -Type Warning
    }
    else
    {
        [Void]$script:lab.Sources.ISOs.Remove($iso)
        Write-PSFMessage "Iso Image '$Name' removed. Lab has $($Script:lab.Sources.ISOs.Count) Iso Image(s) defined"
    }

    Write-LogFunctionExit
}
#endregion Remove-LabIsoImageDefinition
#endregion Iso Image Definition Functions

#region Machine Definition Functions
#region Add-LabDiskDefinition
function Add-LabDiskDefinition
{
    [CmdletBinding()]
    [OutputType([AutomatedLab.Disk])]
    param (
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [ValidateScript( {
                $doesAlreadyExist = Test-Path -Path $_
                if ($doesAlreadyExist)
                {
                    Write-ScreenInfo 'The disk does already exist' -Type Warning
                    return $false
                }
                else
                {
                    return $true
                }
            }
        )]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [int]$DiskSizeInGb = 60,

        [string]$Label,

        [char]$DriveLetter,

        [switch]$UseLargeFRS,

        [long]$AllocationUnitSize = 4KB,

        [switch]$SkipInitialize,

        [switch]$PassThru
    )

    Write-LogFunctionEntry

    if ($null -eq $script:disks)
    {
        $errorMessage = "Create a new lab first using 'New-LabDefinition' before adding disks"
        Write-Error $errorMessage
        Write-LogFunctionExitWithError -Message $errorMessage
        return
    }

    if ($Name)
    {
        if ($script:disks | Where-Object Name -eq $Name)
        {
            $errorMessage = "A disk with the name '$Name' does already exist"
            Write-Error $errorMessage
            Write-LogFunctionExitWithError -Message $errorMessage
            return
        }
    }

    $disk = New-Object -TypeName AutomatedLab.Disk
    $disk.Name = $Name
    $disk.DiskSize = $DiskSizeInGb
    $disk.SkipInitialization = [bool]$SkipInitialize
    $disk.AllocationUnitSize = $AllocationUnitSize
    $disk.UseLargeFRS = $UseLargeFRS
    $disk.DriveLetter = $DriveLetter
    $disk.Label = if ($Label)
    {
        $Label
    }
    else
    {
        'ALData'
    }

    $script:disks.Add($disk)

    Write-PSFMessage "Added disk '$Name' with path '$Path'. Lab now has $($Script:disks.Count) disk(s) defined"

    if ($PassThru)
    {
        $disk
    }

    Write-LogFunctionExit
}
#endregion Add-LabDiskDefinition

#region Add-LabMachineDefinition
function Add-LabMachineDefinition
{
    [CmdletBinding(DefaultParameterSetName = 'Network')]
    [OutputType([AutomatedLab.Machine])]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidatePattern("^([\'\""a-zA-Z0-9-]){1,15}$")]
        [string]$Name,

        [ValidateRange(128MB, 128GB)]
        [double]$Memory,

        [ValidateRange(128MB, 128GB)]
        [double]$MinMemory,

        [ValidateRange(128MB, 128GB)]
        [double]$MaxMemory,

        [ValidateRange(1, 64)]
        [ValidateNotNullOrEmpty()]
        [int]$Processors = 0,

        [ValidatePattern('^([a-zA-Z0-9-_]){2,30}$')]
        [string[]]$DiskName,

        [Alias('OS')]
        [AutomatedLab.OperatingSystem]$OperatingSystem = (Get-LabDefinition).DefaultOperatingSystem,

        [string]$OperatingSystemVersion,

        [Parameter(ParameterSetName = 'Network')]
        [ValidatePattern('^([a-zA-Z0-9])|([ ]){2,244}$')]
        [string]$Network,

        [Parameter(ParameterSetName = 'Network')]
        [ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
        [string]$IpAddress,

        [Parameter(ParameterSetName = 'Network')]
        [ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
        [string]$Gateway,

        [Parameter(ParameterSetName = 'Network')]
        [ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
        [string]$DnsServer1,

        [Parameter(ParameterSetName = 'Network')]
        [ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
        [string]$DnsServer2,

        [Parameter(ParameterSetName = 'NetworkAdapter')]
        [AutomatedLab.NetworkAdapter[]]$NetworkAdapter,

        [switch]$IsDomainJoined,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [switch]$DefaultDomain,

        [System.Management.Automation.PSCredential]$InstallationUserCredential,

        [ValidatePattern("(?=^.{1,254}$)|([\'\""])(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]{1,63}(?<!-)\.)+(?:[a-zA-Z]{2,})$)")]
        [string]$DomainName,

        [AutomatedLab.Role[]]$Roles,

        #Created ValidateSet using: "'" + ([System.Globalization.CultureInfo]::GetCultures([System.Globalization.CultureTypes]::InstalledWin32Cultures).Name -join "', '") + "'" | clip
        [ValidateScript( { $_ -in @([System.Globalization.CultureInfo]::GetCultures([System.Globalization.CultureTypes]::AllCultures).Name) })]
        [string]$UserLocale,

        [AutomatedLab.InstallationActivity[]]$PostInstallationActivity,

        [AutomatedLab.InstallationActivity[]]$PreInstallationActivity,

        [string]$ToolsPath,

        [string]$ToolsPathDestination,

        [AutomatedLab.VirtualizationHost]$VirtualizationHost = 'HyperV',

        [switch]$EnableWindowsFirewall,

        [string]$AutoLogonDomainName,

        [string]$AutoLogonUserName,

        [string]$AutoLogonPassword,

        [hashtable]$AzureProperties,

        [hashtable]$HypervProperties,

        [hashtable]$Notes,

        [switch]$PassThru,

        [string]$ResourceName,

        [switch]$SkipDeployment,

        [string]$AzureRoleSize,

        [string]$TimeZone,

        [string[]]$RhelPackage,

        [string[]]$SusePackage
    )

    begin
    {
        Write-LogFunctionEntry
    }

    process
    {
        $machineRoles = ''
        if ($Roles)
        {
            $machineRoles = " (Roles: $($Roles.Name -join ', '))" 
        }

        $azurePropertiesValidKeys = 'ResourceGroupName', 'UseAllRoleSizes', 'RoleSize', 'LoadBalancerRdpPort', 'LoadBalancerWinRmHttpPort', 'LoadBalancerWinRmHttpsPort', 'LoadBalancerAllowedIp', 'SubnetName', 'UseByolImage', 'AutoshutdownTime', 'AutoshutdownTimezoneId', 'StorageSku'
        $hypervPropertiesValidKeys = 'AutomaticStartAction', 'AutomaticStartDelay', 'AutomaticStopAction'

        if (-not $VirtualizationHost -and -not (Get-LabDefinition).DefaultVirtualizationEngine)
        {
            Throw "Parameter 'VirtualizationHost' is mandatory when calling 'Add-LabMachineDefinition' if no default virtualization engine is specified"
        }

        if (-not $PSBoundParameters.ContainsKey('VirtualizationHost') -and (Get-LabDefinition).DefaultVirtualizationEngine)
        {
            $VirtualizationHost = (Get-LabDefinition).DefaultVirtualizationEngine
        }

        Write-ScreenInfo -Message (("Adding $($VirtualizationHost.ToString().Replace('HyperV', 'Hyper-V')) machine definition '$Name'").PadRight(47) + $machineRoles) -TaskStart

        if (-not (Get-LabDefinition))
        {
            throw 'Please create a lab definition by calling New-LabDefinition before adding machines'
        }

        $script:lab = Get-LabDefinition
        if (($script:lab.DefaultVirtualizationEngine -eq 'Azure' -or $VirtualizationHost -eq 'Azure') -and -not $script:lab.AzureSettings)
        {
            try
            {
                Add-LabAzureSubscription
            }
            catch
            {
                throw "No Azure subscription added yet. Please run 'Add-LabAzureSubscription' first."
            }
        }

        if ($Global:labExported)
        {
            throw 'Lab is already exported. Please create a new lab definition by calling New-LabDefinition before adding machines'
        }

        if (Get-Lab -ErrorAction SilentlyContinue)
        {
            throw 'Lab is already imported. Please create a new lab definition by calling New-LabDefinition before adding machines'
        }

        if (-not $OperatingSystem)
        {
            $os = Get-LabAvailableOperatingSystem -UseOnlyCache -NoDisplay | Where-Object -Property OperatingSystemType -eq 'Windows' | Sort-Object Version | Select-Object -Last 1

            if ($null -ne $os)
            {
                Write-ScreenInfo -Message "No operating system specified. Assuming you want $os ($(Split-Path -Leaf -Path $os.IsoPath))."
                $OperatingSystem = $os
            }
            else
            {
                throw "No operating system was defined for machine '$Name' and no default operating system defined. Please define either of these and retry. Call 'Get-LabAvailableOperatingSystem' to get a list of operating systems added to the lab."
            }
        }

        if ($AzureProperties)
        {
            $illegalKeys = Compare-Object -ReferenceObject $azurePropertiesValidKeys -DifferenceObject ($AzureProperties.Keys | Sort-Object -Unique) |
            Where-Object SideIndicator -eq '=>' |
            Select-Object -ExpandProperty InputObject

            if ($AzureProperties.ContainsKey('StorageSku') -and ($AzureProperties['StorageSku'] -notin (Get-LabConfigurationItem -Name AzureDiskSkus)))
            {
                throw "$($AzureProperties['StorageSku']) is not in $(Get-LabConfigurationItem -Name AzureDiskSkus)"
            }

            if ($illegalKeys)
            {
                throw "The key(s) '$($illegalKeys -join ', ')' are not supported in AzureProperties. Valid keys are '$($azurePropertiesValidKeys -join ', ')'"
            }
        }
        if ($HypervProperties)
        {
            $illegalKeys = Compare-Object -ReferenceObject $hypervPropertiesValidKeys -DifferenceObject ($HypervProperties.Keys | Sort-Object -Unique) |
            Where-Object SideIndicator -eq '=>' |
            Select-Object -ExpandProperty InputObject

            if ($illegalKeys)
            {
                throw "The key(s) '$($illegalKeys -join ', ')' are not supported in HypervProperties. Valid keys are '$($hypervPropertiesValidKeys -join ', ')'"
            }
        }

        if ($global:labNamePrefix)
        {
            $Name = "$global:labNamePrefix$Name" 
        }

        if ($null -eq $script:machines)
        {
            $errorMessage = "Create a new lab first using 'New-LabDefinition' before adding machines"
            Write-Error $errorMessage
            Write-LogFunctionExitWithError -Message $errorMessage
            return
        }

        if ($script:machines | Where-Object Name -eq $Name)
        {
            $errorMessage = "A machine with the name '$Name' does already exist"
            Write-Error $errorMessage
            Write-LogFunctionExitWithError -Message $errorMessage
            return
        }

        if ($script:machines | Where-Object IpAddress.IpAddress -eq $IpAddress)
        {
            $errorMessage = "A machine with the IP address '$IpAddress' does already exist"
            Write-Error $errorMessage
            Write-LogFunctionExitWithError -Message $errorMessage
            return
        }

        $machine = New-Object AutomatedLab.Machine
        $machine.Name = $Name
        $machine.FriendlyName = $ResourceName
        $script:machines.Add($machine)

        if ((Get-LabDefinition).DefaultVirtualizationEngine -and (-not $PSBoundParameters.ContainsKey('VirtualizationHost')))
        {
            $VirtualizationHost = (Get-LabDefinition).DefaultVirtualizationEngine
        }

        if ($VirtualizationHost -eq 'Azure')
        {
            $script:lab.AzureSettings.LoadBalancerPortCounter++
            $machine.LoadBalancerRdpPort = $script:lab.AzureSettings.LoadBalancerPortCounter
            $script:lab.AzureSettings.LoadBalancerPortCounter++
            $machine.LoadBalancerWinRmHttpPort = $script:lab.AzureSettings.LoadBalancerPortCounter
            $script:lab.AzureSettings.LoadBalancerPortCounter++
            $machine.LoadBalancerWinrmHttpsPort = $script:lab.AzureSettings.LoadBalancerPortCounter
        }

        if ($InstallationUserCredential)
        {
            $installationUser = New-Object AutomatedLab.User($InstallationUserCredential.UserName, $InstallationUserCredential.GetNetworkCredential().Password)
        }
        else
        {
            if ((Get-LabDefinition).DefaultInstallationCredential)
            {
                $installationUser = New-Object AutomatedLab.User((Get-LabDefinition).DefaultInstallationCredential.UserName, (Get-LabDefinition).DefaultInstallationCredential.Password)
            }
            else
            {
                switch ($VirtualizationHost)
                {
                    'HyperV'
                    {
                        $installationUser = New-Object AutomatedLab.User('Administrator', 'Somepass1') 
                    }
                    'Azure'
                    {
                        $installationUser = New-Object AutomatedLab.User('Install', 'Somepass1') 
                    }
                    Default
                    {
                        $installationUser = New-Object AutomatedLab.User('Administrator', 'Somepass1') 
                    }
                }
            }
        }
        $machine.InstallationUser = $installationUser

        $machine.IsDomainJoined = $false

        if ($PSBoundParameters.ContainsKey('DefaultDomain') -and $DefaultDomain)
        {
            if (-not (Get-LabDomainDefinition))
            {
                if ($VirtualizationHost -eq 'Azure')
                {
                    Add-LabDomainDefinition -Name 'contoso.com' -AdminUser Install -AdminPassword 'Somepass1'
                }
                else
                {
                    Add-LabDomainDefinition -Name 'contoso.com' -AdminUser Administrator -AdminPassword 'Somepass1'
                }
            }

            $DomainName = (Get-LabDomainDefinition)[0].Name
        }

        if ($DomainName -or ($Roles -and $Roles.Name -match 'DC$'))
        {
            $machine.IsDomainJoined = $true

            if ($Roles.Name -eq 'RootDC' -or $Roles.Name -eq 'DC')
            {
                if (-not $DomainName)
                {
                    if (-not (Get-LabDomainDefinition))
                    {
                        $DomainName = 'contoso.com'
                        switch ($VirtualizationHost)
                        {
                            'Azure'
                            {
                                Add-LabDomainDefinition -Name $DomainName -AdminUser Install -AdminPassword Somepass1 
                            }
                            'HyperV'
                            {
                                Add-LabDomainDefinition -Name $DomainName -AdminUser Administrator -AdminPassword Somepass1 
                            }
                            'VMware'
                            {
                                Add-LabDomainDefinition -Name $DomainName -AdminUser Administrator -AdminPassword Somepass1 
                            }
                        }
                    }
                    else
                    {
                        throw 'Domain name not specified for Root Domain Controller'
                    }
                }
            }
            elseif ('FirstChildDC' -in $Roles.Name)
            {
                $role = $Roles | Where-Object Name -eq FirstChildDC
                $containsProperties = [boolean]$role.Properties
                if ($containsProperties)
                {
                    $parentDomainInProperties = $role.Properties.ParentDomain
                    $newDomainInProperties = $role.Properties.NewDomain

                    Write-PSFMessage -Message "Machine contains custom properties for FirstChildDC: 'ParentDomain'='$parentDomainInProperties', 'NewDomain'='$newDomainInProperties'"
                }

                if ((-not $containsProperties) -and (-not $DomainName))
                {
                    Write-PSFMessage -Message 'Nothing specified (no DomainName nor ANY Properties). Giving up'

                    throw 'Domain name not specified for Child Domain Controller'
                }

                if ((-not $DomainName) -and ((-not $parentDomainInProperties -or (-not $newDomainInProperties))))
                {
                    Write-PSFMessage -Message 'No DomainName or Properties for ParentName and NewDomain specified. Giving up'

                    throw 'Domain name not specified for Child Domain Controller'
                }

                if ($containsProperties -and $parentDomainInProperties -and $newDomainInProperties -and (-not $DomainName))
                {
                    Write-PSFMessage -Message 'Properties specified but DomainName is not. Then populate DomainName based on Properties'

                    $DomainName = "$($role.Properties.NewDomain).$($role.Properties.ParentDomain)"
                    Write-PSFMessage -Message "Machine contains custom properties for FirstChildDC but DomainName parameter is not specified. Setting now to '$DomainName'"
                }
                elseif (((-not $containsProperties) -or ($containsProperties -and (-not $parentDomainInProperties) -and (-not $newDomainInProperties))) -and $DomainName)
                {
                    $newDomainName = $DomainName.Substring(0, $DomainName.IndexOf('.'))
                    $parentDomainName = $DomainName.Substring($DomainName.IndexOf('.') + 1)

                    Write-PSFMessage -Message 'No Properties specified (or properties for ParentName and NewDomain omitted) but DomainName parameter is specified. Calculating/updating ParentDomain and NewDomain properties'
                    if (-not $containsProperties)
                    {
                        $role.Properties = @{ 'NewDomain' = $newDomainName }
                        $role.Properties.Add('ParentDomain', $parentDomainName)
                    }
                    else
                    {
                        if (-not $role.Properties.ContainsKey('NewDomain'))
                        {
                            $role.Properties.Add('NewDomain', $newDomainName)
                        }

                        if (-not $role.Properties.ContainsKey('ParentDomain'))
                        {
                            $role.Properties.Add('ParentDomain', $parentDomainName)
                        }
                    }
                    $parentDomainInProperties = $role.Properties.ParentDomain
                    $newDomainInProperties = $role.Properties.NewDomain
                    Write-PSFMessage -Message "ParentDomain now set to '$parentDomainInProperties'"
                    Write-PSFMessage -Message "NewDomain now set to '$newDomainInProperties'"
                }
            }

            if (-not (Get-LabDomainDefinition | Where-Object Name -eq $DomainName))
            {
                if ($VirtualizationHost -eq 'Azure')
                {
                    Add-LabDomainDefinition -Name $DomainName -AdminUser Install -AdminPassword 'Somepass1'
                }
                else
                {
                    Add-LabDomainDefinition -Name $DomainName -AdminUser Administrator -AdminPassword 'Somepass1'
                }
            }
            $machine.DomainName = $DomainName
        }

        if (-not $OperatingSystem.Version)
        {
            if ($OperatingSystemVersion)
            {
                $OperatingSystem.Version = $OperatingSystemVersion
            }
            else
            {
                throw "Could not identify the version of operating system '$($OperatingSystem.OperatingSystemName)' assigned to machine '$Name'. The version is required to continue."
            }
        }

        switch ($OperatingSystem.Version.ToString(2))
        {
            '6.0'
            {
                $level = 'Win2008' 
            }
            '6.1'
            {
                $level = 'Win2008R2' 
            }
            '6.2'
            {
                $level = 'Win2012' 
            }
            '6.3'
            {
                $level = 'Win2012R2' 
            }
            '6.4'
            {
                $level = 'WinThreshold' 
            }
            '10.0'
            {
                $level = 'WinThreshold' 
            }
        }

        $role = $roles | Where-Object Name -in ('RootDC', 'FirstChildDC', 'DC')
        if ($role)
        {
            if ($role.Properties)
            {
                if ($role.Name -eq 'RootDC')
                {
                    if (-not $role.Properties.ContainsKey('ForestFunctionalLevel'))
                    {
                        $role.Properties.Add('ForestFunctionalLevel', $level)
                    }
                }

                if ($role.Name -eq 'RootDC' -or $role.Name -eq 'FirstChildDC')
                {
                    if (-not $role.Properties.ContainsKey('DomainFunctionalLevel'))
                    {
                        $role.Properties.Add('DomainFunctionalLevel', $level)
                    }
                }
            }
            else
            {
                if ($role.Name -eq 'RootDC')
                {
                    $role.Properties = @{'ForestFunctionalLevel' = $level }
                    $role.Properties.Add('DomainFunctionalLevel', $level)
                }
                elseif ($role.Name -eq 'FirstChildDC')
                {
                    $role.Properties = @{'DomainFunctionalLevel' = $level }
                }
            }
        }

        #Virtual network detection and automatic creation
        if ($VirtualizationHost -eq 'Azure')
        {
            if (-not (Get-LabVirtualNetworkDefinition))
            {
                #No virtual networks has been specified

                Write-ScreenInfo -Message 'No virtual networks specified. Creating a network automatically' -Type Warning
                if (-not ($Global:existingAzureNetworks))
                {
                    $Global:existingAzureNetworks = Get-AzVirtualNetwork
                }

                #Virtual network name will be same as lab name
                $autoNetworkName = (Get-LabDefinition).Name

                #Priority 1. Check for existence of an Azure virtual network with same name as network name
                $existingNetwork = $Global:existingAzureNetworks | Where-Object { $_.Name -eq $autoNetworkName }
                if ($existingNetwork)
                {
                    Write-PSFMessage -Message 'Virtual switch already exists with same name as lab being deployed. Trying to re-use.'
                    $addressSpace = $existingNetwork.AddressSpace.AddressPrefixes

                    Write-ScreenInfo -Message "Creating virtual network '$autoNetworkName' with address spacee '$addressSpace'" -Type Warning
                    Add-LabVirtualNetworkDefinition -Name $autoNetworkName -AddressSpace $addressSpace[0]

                    #First automatically assigned IP address will be following+1
                    $addressSpaceIpAddress = "$($addressSpace.Split('/')[0].Split('.')[0..2] -Join '.').5"
                    $script:autoIPAddress = [AutomatedLab.IPAddress]$addressSpaceIpAddress

                    $notDone = $false
                }
                else
                {
                    Write-PSFMessage -Message 'No Azure virtual network found with same name as network name. Attempting to find unused network in the range 192.168.2.x-192.168.255.x'

                    $networkFound = $false
                    [int]$octet = 1
                    do
                    {
                        $octet++

                        $azureInUse = $false
                        foreach ($azureNetwork in $Global:existingAzureNetworks.AddressSpace.AddressPrefixes)
                        {
                            if (Test-IpInSameSameNetwork -Ip1 "192.168.$octet.0/24" -Ip2 $azureNetwork)
                            {
                                $azureInUse = $true
                            }
                        }
                        if ($azureInUse)
                        {
                            Write-PSFMessage -Message "Network '192.168.$octet.0/24' is in use by an existing Azure virtual network"
                            continue
                        }

                        $networkFound = $true
                    }
                    until ($networkFound -or $octet -ge 255)

                    if ($networkFound)
                    {
                        Write-ScreenInfo "Creating virtual network with name '$autoNetworkName' and address space '192.168.$octet.1/24'" -Type Warning
                        Add-LabVirtualNetworkDefinition -Name $autoNetworkName  -AddressSpace "192.168.$octet.1/24"
                    }
                    else
                    {
                        throw 'Virtual network could not be created. Please create virtual network manually by calling Add-LabVirtualNetworkDefinition (after calling New-LabDefinition)'
                    }

                    #First automatically asigned IP address will be following+1
                    $script:autoIPAddress = ([AutomatedLab.IPAddress]("192.168.$octet.5")).AddressAsString
                }

                #throw 'No virtual network is defined. Please call Add-LabVirtualNetworkDefinition before adding machines but after calling New-LabDefinition'
            }
        }
        elseif ($VirtualizationHost -eq 'HyperV')
        {
            Write-PSFMessage -Message 'Detect if a virtual switch already exists with same name as lab being deployed. If so, use this switch for defining network name and address space.'

            #this takes a lot of time hence it should be called only once in a deployment
            if (-not $script:existingHyperVVirtualSwitches)
            {
                $script:existingHyperVVirtualSwitches = Get-LabVirtualNetwork
            }

            $networkDefinitions = Get-LabVirtualNetworkDefinition

            if (-not $networkDefinitions)
            {
                #No virtual networks has been specified

                Write-ScreenInfo -Message 'No virtual networks specified. Creating a network automatically' -Type Warning

                #Virtual network name will be same as lab name
                $autoNetworkName = (Get-LabDefinition).Name

                #Priority 1. Check for existence of Hyper-V virtual switch with same name as network name
                $existingNetwork = $existingHyperVVirtualSwitches | Where-Object Name -eq $autoNetworkName
                if ($existingNetwork)
                {
                    Write-PSFMessage -Message 'Virtual switch already exists with same name as lab being deployed. Trying to re-use.'

                    Write-ScreenInfo -Message "Using virtual network '$autoNetworkName' with address space '$addressSpace'" -Type Info
                    Add-LabVirtualNetworkDefinition -Name $autoNetworkName -AddressSpace $existingNetwork.AddressSpace
                }
                else
                {
                    Write-PSFMessage -Message 'No virtual switch found with same name as network name. Attempting to find unused network'

                    $addressSpace = Get-LabAvailableAddresseSpace

                    if ($addressSpace)
                    {
                        Write-ScreenInfo "Creating network '$autoNetworkName' with address space '$addressSpace'" -Type Warning
                        Add-LabVirtualNetworkDefinition -Name $autoNetworkName  -AddressSpace $addressSpace
                    }
                    else
                    {
                        throw 'Virtual network could not be created. Please create virtual network manually by calling Add-LabVirtualNetworkDefinition (after calling New-LabDefinition)'
                    }
                }
            }
            else
            {
                Write-PSFMessage -Message 'One or more virtual network(s) has been specified.'

                #Using first specified virtual network '$($networkDefinitions[0])' with address space '$($networkDefinitions[0].AddressSpace)'."

                <#
                        if ($script:autoIPAddress)
                        {
                        #Network already created and IP range already found
                        Write-PSFMessage -Message 'Network already created and IP range already found'
                        }
                        else
                        {
                #>


                foreach ($networkDefinition in $networkDefinitions)
                {
                    #check for an virtual switch having already the name of the new network switch
                    $existingNetwork = $existingHyperVVirtualSwitches | Where-Object Name -eq $networkDefinition.ResourceName

                    #does the current network definition has an address space assigned
                    if ($networkDefinition.AddressSpace)
                    {
                        Write-PSFMessage -Message "Virtual network '$($networkDefinition.ResourceName)' specified with address space '$($networkDefinition.AddressSpace)'"

                        #then check if the existing network has the same address space as the new one and throw an exception if not
                        if ($existingNetwork)
                        {
                            if ($existingNetwork.SwitchType -eq 'External')
                            {
                                #Different address spaces for different labs reusing an existing External virtual switch is permitted, however this requires knowledge and support
                                # for switching / routing fabrics external to AL and the host. Note to the screen this is an advanced configuration.
                                if ($networkDefinition.AddressSpace -ne $existingNetwork.AddressSpace)
                                {
                                    Write-ScreenInfo "Address space defined '$($networkDefinition.AddressSpace)' for network '$networkDefinition' is different from the address space '$($existingNetwork.AddressSpace)' used by currently existing Hyper-V switch with same name." -Type Warning
                                    Write-ScreenInfo "This is an advanced configuration, ensure external switching and routing is configured correctly" -Type Warning
                                    Write-PSFMessage -Message 'Existing External Hyper-V virtual switch found with different address space. This is an allowed advanced configuration'
                                }
                                else
                                {
                                    Write-PSFMessage -Message 'Existing External Hyper-V virtual switch found with same name and address space as first virtual network specified. Using this.'
                                }
                            }
                            else
                            {
                                if ($networkDefinition.AddressSpace -ne $existingNetwork.AddressSpace)
                                {
                                    throw "Address space defined '$($networkDefinition.AddressSpace)' for network '$networkDefinition' is different from the address space '$($existingNetwork.AddressSpace)' used by currently existing Hyper-V switch with same name. Cannot continue."
                                }
                            }
                        }
                        else
                        {
                            #if the network does not already exist, verify if the address space if not already assigned
                            $otherHypervSwitch = $existingHyperVVirtualSwitches | Where-Object AddressSpace -eq $networkDefinition.AddressSpace
                            if ($otherHypervSwitch)
                            {
                                throw "Another Hyper-V virtual switch '$($otherHypervSwitch.Name)' is using address space specified in this lab ($($networkDefinition.AddressSpace)). Cannot continue."
                            }

                            #and also verify that the new address space is not overlapping with an exsiting one
                            $otherHypervSwitch = $existingHyperVVirtualSwitches |
                            Where-Object { $_.AddressSpace } |
                            Where-Object { [AutomatedLab.IPNetwork]::Overlap($_.AddressSpace, $networkDefinition.AddressSpace) } |
                            Select-Object -First 1

                            if ($otherHypervSwitch)
                            {
                                throw "The Hyper-V virtual switch '$($otherHypervSwitch.Name)' is using an address space ($($otherHypervSwitch.AddressSpace)) that overlaps with the specified one in this lab ($($networkDefinition.AddressSpace)). Cannot continue."
                            }

                            Write-PSFMessage -Message 'Address space specified is valid'
                        }
                    }
                    else
                    {
                        if ($networkDefinition.SwitchType -eq 'External')
                        {
                            Write-PSFMessage 'External network interfaces will not get automatic IP addresses'
                            continue
                        }

                        Write-PSFMessage -Message "Virtual network '$networkDefinition' specified but without address space specified"

                        if ($existingNetwork)
                        {
                            Write-PSFMessage -Message "Existing Hyper-V virtual switch found with same name as first virtual network name. Using it with address space '$($existingNetwork.AddressSpace)'."
                            $networkDefinition.AddressSpace = $existingNetwork.AddressSpace
                        }
                        else
                        {
                            Write-PSFMessage -Message 'No Hyper-V virtual switch found with same name as lab name. Attempting to find unused network.'

                            $addressSpace = Get-LabAvailableAddresseSpace

                            if ($addressSpace)
                            {
                                Write-ScreenInfo "Using network '$networkDefinition' with address space '$addressSpace'" -Type Warning
                                $networkDefinition.AddressSpace = $addressSpace
                            }
                            else
                            {
                                throw 'Virtual network could not be used. Please create virtual network manually by calling Add-LabVirtualNetworkDefinition (after calling New-LabDefinition)'
                            }
                        }
                    }
                }
            }
        }

        if ($Network)
        {
            $networkDefinition = Get-LabVirtualNetworkDefinition -Name $network
            if (-not $networkDefinition)
            {
                throw "A virtual network definition with the name '$Network' could not be found. To get a list of network definitions, use 'Get-LabVirtualNetworkDefinition'"
            }

            if ($networkDefinition.SwitchType -eq 'External' -and -not $networkDefinition.AddressSpace -and -not $IpAddress)
            {
                $useDhcp = $true
            }

            $NetworkAdapter = New-LabNetworkAdapterDefinition -VirtualSwitch $networkDefinition.Name -UseDhcp:$useDhcp
        }
        elseif (-not $NetworkAdapter)
        {
            if ((Get-LabVirtualNetworkDefinition).Count -eq 1)
            {
                $networkDefinition = Get-LabVirtualNetworkDefinition

                $NetworkAdapter = New-LabNetworkAdapterDefinition -VirtualSwitch $networkDefinition.Name

            }
            else
            {
                throw "Network cannot be determined for machine '$machine'. Either no networks is defined or more than one network is defined while network is not specified when calling this function"
            }
        }

        $machine.HostType = $VirtualizationHost

        foreach ($adapter in $NetworkAdapter)
        {
            $adapterVirtualNetwork = Get-LabVirtualNetworkDefinition -Name $adapter.VirtualSwitch

            #if there is no IPV4 address defined on the adapter
            if (-not $adapter.IpV4Address)
            {
                #if there is also no IP address defined on the machine and the adapter is not set to DHCP and the network the adapter is connected to does not know about an address space we cannot continue
                if (-not $IpAddress -and -not $adapter.UseDhcp -and -not $adapterVirtualNetwork.AddressSpace)
                {
                    throw "The virtual network '$adapterVirtualNetwork' defined on machine '$machine' does not have an IP address assigned and is not set to DHCP"
                }
                elseif ($IpAddress)
                {
                    if ($AzureProperties.SubnetName -and $adapterVirtualNetwork.Subnets.Count -gt 0)
                    {
                        $chosenSubnet = $adapterVirtualNetwork.Subnets | Where-Object Name -EQ $AzureProperties.SubnetName
                        if (-not $chosenSubnet)
                        {
                            throw ('No fitting subnet available. Subnet {0} could not be found in the list of available subnets {1}' -f $AzureProperties.SubnetName, ($adapterVirtualNetwork.Subnets.Name -join ','))
                        }

                        $adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($IpAddress, $chosenSubnet.AddressSpace.Netmask))
                    }
                    elseif ($VirtualizationHost -eq 'Azure' -and $adapterVirtualNetwork.Subnets.Count -gt 0 -and -not $AzureProperties.SubnetName)
                    {
                        # No default subnet and no name selected. Chose fitting subnet.
                        $chosenSubnet = $adapterVirtualNetwork.Subnets | Where-Object { $IpAddress -in (Get-NetworkRange -IPAddress $_.AddressSpace.IpAddress -SubnetMask $_.AddressSpace.Netmask) }
                        if (-not $chosenSubnet)
                        {
                            throw ('No fitting subnet available. No subnet was found with a valid address range. {0} was not in the range of these subnets: ' -f $IpAddress, ($adapterVirtualNetwork.Subnets.Name -join ','))
                        }

                        $adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($IpAddress, $chosenSubnet.AddressSpace.Netmask))
                    }
                    else
                    {
                        $adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($IpAddress, $adapterVirtualNetwork.AddressSpace.Netmask))
                    }
                }
                elseif (-not $adapter.UseDhcp)
                {
                    $ip = $adapterVirtualNetwork.NextIpAddress()

                    if ($AzureProperties.SubnetName -and $adapterVirtualNetwork.Subnets.Count -gt 0)
                    {
                        $chosenSubnet = $adapterVirtualNetwork.Subnets | Where-Object Name -EQ $AzureProperties.SubnetName
                        if (-not $chosenSubnet)
                        {
                            throw ('No fitting subnet available. Subnet {0} could not be found in the list of available subnets {1}' -f $AzureProperties.SubnetName, ($adapterVirtualNetwork.Subnets.Name -join ','))
                        }

                        $adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($ip, $chosenSubnet.AddressSpace.Netmask))
                    }
                    elseif ($VirtualizationHost -eq 'Azure' -and $adapterVirtualNetwork.Subnets.Count -gt 0 -and -not $AzureProperties.SubnetName)
                    {
                        # No default subnet and no name selected. Chose fitting subnet.
                        $chosenSubnet = $adapterVirtualNetwork.Subnets | Where-Object { $ip -in (Get-NetworkRange -IPAddress $_.AddressSpace.IpAddress -SubnetMask $_.AddressSpace.Netmask) }
                        if (-not $chosenSubnet)
                        {
                            throw ('No fitting subnet available. No subnet was found with a valid address range. {0} was not in the range of these subnets: ' -f $IpAddress, ($adapterVirtualNetwork.Subnets.Name -join ','))
                        }

                        $adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($ip, $chosenSubnet.AddressSpace.Netmask))
                    }
                    else
                    {
                        $adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($ip, $adapterVirtualNetwork.AddressSpace.Netmask))
                    }
                }
            }

            if ($DnsServer1)
            {
                $adapter.Ipv4DnsServers.Add($DnsServer1) 
            }
            if ($DnsServer2)
            {
                $adapter.Ipv4DnsServers.Add($DnsServer2) 
            }

            #if the virtual network is not external, the machine is not an Azure one, is domain joined and there is no DNS server configured
            if ($adapter.VirtualSwitch.SwitchType -ne 'External' -and
                $machine.HostType -ne 'Azure' -and
                #$machine.IsDomainJoined -and
                -not $adapter.UseDhcp -and
                -not ($DnsServer1 -or $DnsServer2
                ))
            {
                $adapter.Ipv4DnsServers.Add('0.0.0.0')
            }

            if ($Gateway)
            {
                $adapter.Ipv4Gateway.Add($Gateway) 
            }

            $machine.NetworkAdapters.Add($adapter)
        }

        Repair-LabDuplicateIpAddresses

        if ($processors -eq 0)
        {
            $processors = 1
            if (-not $script:processors)
            {
                $script:processors = if ($IsLinux -or $IsMacOs)
                {
                    $coreInf = Get-Content /proc/cpuinfo | Select-String 'siblings\s+:\s+\d+' | Select-Object -Unique
                    [int]($coreInf -replace 'siblings\s+:\s+')
                }
                else
                {
                    (Get-CimInstance -Namespace Root\CIMv2 -Class win32_processor | Measure-Object NumberOfLogicalProcessors -Sum).Sum
                }
            }
            if ($script:processors -ge 2)
            {
                $machine.Processors = 2
            }
        }
        else
        {
            $machine.Processors = $Processors
        }


        if ($PSBoundParameters.ContainsKey('Memory'))
        {
            $machine.Memory = $Memory
        }
        else
        {
            $machine.Memory = 1

            #Memory weight based on role of machine
            $machine.Memory = 1
            foreach ($role in $Roles)
            {
                if ((Get-LabConfigurationItem -Name "MemoryWeight_$($role.Name)") -gt $machine.Memory)
                {
                    $machine.Memory = Get-LabConfigurationItem -Name "MemoryWeight_$($role.Name)"
                }
            }
        }

        if ($PSBoundParameters.ContainsKey('MinMemory'))
        {
            $machine.MinMemory = $MinMemory
        }
        if ($PSBoundParameters.ContainsKey('MaxMemory'))
        {
            $machine.MaxMemory = $MaxMemory
        }

        $machine.EnableWindowsFirewall = $EnableWindowsFirewall

        $machine.AutoLogonDomainName = $AutoLogonDomainName
        $machine.AutoLogonUserName = $AutoLogonUserName
        $machine.AutoLogonPassword = $AutoLogonPassword

        if ($machine.HostType -eq 'HyperV')
        {
            if ($RhelPackage)
            {
                $machine.LinuxPackageGroup = $RhelPackage
            }
            if ($SusePackage)
            {
                $machine.LinuxPackageGroup = $SusePackage
            }

            if ($OperatingSystemVersion)
            {
                $os = Get-LabAvailableOperatingSystem -NoDisplay | Where-Object { $_.OperatingSystemName -eq $OperatingSystem -and $_.Version -eq $OperatingSystemVersion }
            }
            else
            {
                $os = Get-LabAvailableOperatingSystem -NoDisplay | Where-Object OperatingSystemName -eq $OperatingSystem
                if ($os.Count -gt 1)
                {
                    $os = $os | Group-Object -Property Version | Sort-Object -Property Name -Descending | Select-Object -First 1 | Select-Object -ExpandProperty Group
                    Write-ScreenInfo "The operating system '$OperatingSystem' is available multiple times. Choosing the one with the highest version ($($os[0].Version))" -Type Warning
                }

                if ($os.Count -gt 1)
                {
                    $os = $os | Sort-Object -Property { (Get-Item -Path $_.IsoPath).LastWriteTime } -Descending | Select-Object -First 1
                    Write-ScreenInfo "The operating system '$OperatingSystem' with the same version is available on multiple images. Choosing the one with the highest LastWriteTime to honor updated images ($((Get-Item -Path $os.IsoPath).LastWriteTime))" -Type Warning
                }
            }

            if (-not $os)
            {
                if ($OperatingSystemVersion)
                {
                    throw "The operating system '$OperatingSystem' for machine '$Name' with version '$OperatingSystemVersion' could not be found in the available operating systems. Call 'Get-LabAvailableOperatingSystem' to get a list of operating systems added to the lab."
                }
                else
                {
                    throw "The operating system '$OperatingSystem' for machine '$Name' could not be found in the available operating systems. Call 'Get-LabAvailableOperatingSystem' to get a list of operating systems added to the lab."
                }
            }
            $machine.OperatingSystem = $os
        }
        elseif ($machine.HostType -eq 'Azure')
        {
            $machine.OperatingSystem = $OperatingSystem
        }
        elseif ($machine.HostType -eq 'VMWare')
        {
            $machine.OperatingSystem = $OperatingSystem
        }

        if (-not $TimeZone)
        {
            $TimeZone = (Get-TimeZone).StandardName
        }
        $machine.Timezone = $TimeZone

        if (-not $UserLocale)
        {
            $UserLocale = (Get-Culture).Name -replace '-POSIX'
        }
        $machine.UserLocale = $UserLocale

        $machine.Roles = $Roles
        $machine.PostInstallationActivity = $PostInstallationActivity
        $machine.PreInstallationActivity = $PreInstallationActivity

        if ($HypervProperties)
        {
            $machine.HypervProperties = $HypervProperties
        }

        if ($AzureProperties)
        {
            $machine.AzureProperties = $AzureProperties
        }
        if ($AzureRoleSize)
        {
            if (-not $AzureProperties)
            {
                $machine.AzureProperties = @{ RoleSize = $AzureRoleSize }
            }
            else
            {
                $machine.AzureProperties.RoleSize = $AzureRoleSize
            }
        }

        $machine.ToolsPath = $ToolsPath.Replace('<machinename>', $machine.Name)

        $machine.ToolsPathDestination = $ToolsPathDestination

        $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Disk
        $machine.Disks = New-Object $type

        if ($DiskName)
        {
            foreach ($disk in $DiskName)
            {
                $labDisk = $script:disks | Where-Object Name -eq $disk
                if (-not $labDisk)
                {
                    throw "The disk with the name '$disk' has not yet been added to the lab. Do this first using the cmdlet 'Add-LabDiskDefinition'"
                }
                $machine.Disks.Add($labDisk)
            }
        }

        $machine.SkipDeployment = $SkipDeployment
    }

    end
    {
        if ($Notes)
        {
            $machine.Notes = $Notes
        }

        Write-ScreenInfo -Message 'Done' -TaskEnd

        if ($PassThru)
        {
            $machine
        }

        Write-LogFunctionExit
    }
}
#endregion Add-LabMachineDefinition

#region Get-LabMachineDefinition
function Get-LabMachineDefinition
{
    [CmdletBinding(DefaultParameterSetName = 'ByName')]
    [OutputType([AutomatedLab.Machine])]

    param (
        [Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [string[]]$ComputerName,

        [Parameter(Mandatory, ParameterSetName = 'ByRole')]
        [AutomatedLab.Roles]$Role,

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

    begin
    {
        #required to suporess verbose messages, warnings and errors
        Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

        Write-LogFunctionEntry

        $result = @()
    }

    process
    {
        if ($PSCmdlet.ParameterSetName -eq 'ByName')
        {
            if ($ComputerName)
            {
                foreach ($n in $ComputerName)
                {
                    $machine = $Script:machines | Where-Object Name -in $n
                    if (-not $machine)
                    {
                        continue
                    }

                    $result += $machine
                }
            }
            else
            {
                $result = $Script:machines
            }
        }

        if ($PSCmdlet.ParameterSetName -eq 'ByRole')
        {
            $result = $Script:machines |
            Where-Object { $_.Roles.Name } |
            Where-Object { $_.Roles | Where-Object { $Role.HasFlag([AutomatedLab.Roles]$_.Name) } }

            if (-not $result)
            {
                return
            }
        }

        if ($PSCmdlet.ParameterSetName -eq 'All')
        {
            $result = $Script:machines
        }
    }

    end
    {
        $result
    }
}
#endregion Get-LabMachineDefinition

#region Remove-LabMachineDefinition
function Remove-LabMachineDefinition
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Name
    )

    Write-LogFunctionEntry

    $machine = $script:machines | Where-Object Name -eq $Name

    if (-not $machine)
    {
        Write-ScreenInfo "There is no machine defined with the name '$Name'" -Type Warning
    }
    else
    {
        [Void]$script:machines.Remove($machine)
        Write-PSFMessage "Machine '$Name' removed. Lab has $($Script:machines.Count) machine(s) defined"
    }

    Write-LogFunctionExit
}
#endregion Remove-LabMachineDefinition

#region Get-LabMachineRoleDefinition
function Get-LabMachineRoleDefinition
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [AutomatedLab.Roles]
        $Role,

        [hashtable]
        $Properties,

        [switch]
        $Syntax
    )

    $roleObjects = @()
    $availableRoles = [Enum]::GetNames([AutomatedLab.Roles])
    $config = Get-LabConfigurationItem -Name ValidationSettings

    foreach ($availableRole in $availableRoles)
    {
        if ($Role.HasFlag([AutomatedLab.Roles]$availableRole))
        {            
            if ($Syntax.IsPresent -and $config.ValidRoleProperties.Contains($availableRole.ToString()))
            {
                $roleObjects += "Get-LabMachineRoleDefinition -Role $availableRole -Properties @{`r`n$($config.ValidRoleProperties[$availableRole.ToString()] -join `"='value'`r`n`")='value'`r`n}`r`n"
            }
            elseif ($Syntax.IsPresent -and -not $config.ValidRoleProperties.Contains($availableRole.ToString()))
            {
                $roleObjects += "Get-LabMachineRoleDefinition -Role $availableRole`r`n"
            }
            else
            {
                $roleObject = New-Object -TypeName AutomatedLab.Role
                $roleObject.Name = $availableRole
                $roleObject.Properties = $Properties

                $roleObjects += $roleObject
            }
        }
    }

    return $roleObjects
}
#endregion Get-LabMachineRoleDefinition

#region Get-LabPostInstallationActivity
function Get-LabInstallationActivity
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ParameterSetName = 'FileContentDependencyRemoteScript')]
        [Parameter(Mandatory, ParameterSetName = 'FileContentDependencyLocalScript')]
        [string]$DependencyFolder,

        [Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyRemoteScript')]
        [Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyLocalScript')]
        [string]$IsoImage,

        [Parameter(ParameterSetName = 'FileContentDependencyRemoteScript')]
        [Parameter(ParameterSetName = 'FileContentDependencyLocalScript')]
        [Parameter(ParameterSetName = 'CustomRole')]
        [switch]$KeepFolder,

        [Parameter(Mandatory, ParameterSetName = 'FileContentDependencyRemoteScript')]
        [Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyRemoteScript')]
        [string]$ScriptFileName,

        [Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyLocalScript')]
        [Parameter(Mandatory, ParameterSetName = 'FileContentDependencyLocalScript')]
        [string]$ScriptFilePath,

        [Parameter(ParameterSetName = 'CustomRole')]
        [hashtable]$Properties,

        [System.Management.Automation.PSVariable[]]$Variable,
    
        [System.Management.Automation.FunctionInfo[]]$Function,

        [switch]$DoNotUseCredSsp,

        [string]$CustomRole
    )

    begin
    {
        Write-LogFunctionEntry
        $activity = New-Object -TypeName AutomatedLab.InstallationActivity
        if ($Variable) { $activity.SerializedVariables = $Variable | ConvertTo-PSFClixml}
        if ($Function) { $activity.SerializedFunctions = $Function | ConvertTo-PSFClixml}
        if (-not $Properties)
        {
            $Properties = @{ } 
        }
    }

    process
    {
        if ($PSCmdlet.ParameterSetName -like 'FileContentDependency*')
        {
            $activity.DependencyFolder = $DependencyFolder
            $activity.KeepFolder = $KeepFolder.ToBool()
            if ($ScriptFilePath)
            {
                $activity.ScriptFilePath = $ScriptFilePath
            }
            else
            {
                $activity.ScriptFileName = $ScriptFileName
            }
        }
        elseif ($PSCmdlet.ParameterSetName -like 'IsoImage*')
        {
            $activity.IsoImage = $IsoImage
            if ($ScriptFilePath)
            {
                $activity.ScriptFilePath = $ScriptFilePath
            }
            else
            {
                $activity.ScriptFileName = $ScriptFileName
            }
        }
        elseif ($PSCmdlet.ParameterSetName -eq 'CustomRole')
        {
            $activity.DependencyFolder = Join-Path -Path (Join-Path -Path (Get-LabSourcesLocation -Local) -ChildPath 'CustomRoles') -ChildPath $CustomRole
            $activity.KeepFolder = $KeepFolder.ToBool()
            $activity.ScriptFileName = "$CustomRole.ps1"
            $activity.IsCustomRole = $true

            #The next sections compares the given custom role properties with with the custom role parameters.
            #Custom role parameters are taken form the main role script as well as the HostStart.ps1 and the HostEnd.ps1
            $scripts = $activity.ScriptFileName, 'HostStart.ps1', 'HostEnd.ps1'
            $unknownParameters = New-Object System.Collections.Generic.List[string]

            foreach ($script in $scripts)
            {
                $scriptFullName = Join-Path -Path $activity.DependencyFolder -ChildPath $script
                if (-not (Test-Path -Path $scriptFullName))
                {
                    continue
                }
                $scriptInfo = Get-Command -Name $scriptFullName
                $commonParameters = [System.Management.Automation.Internal.CommonParameters].GetProperties().Name
                $parameters = $scriptInfo.Parameters.GetEnumerator() | Where-Object Key -NotIn $commonParameters

                #If the custom role knows about a ComputerName parameter and if there is no value defined by the user, add add empty value now.
                #Later that will be filled with the computer name of the computer the role is assigned to when the HostStart and the HostEnd scripts are invoked.
                if ($Properties)
                {
                    if (($parameters | Where-Object Key -eq 'ComputerName') -and -not $Properties.ContainsKey('ComputerName'))
                    {
                        $Properties.Add('ComputerName', '')
                    }
                }

                #test if all mandatory parameters are defined
                foreach ($parameter in $parameters)
                {
                    if ($parameter.Value.Attributes.Mandatory -and -not $properties.ContainsKey($parameter.Key))
                    {
                        Write-Error "There is no value defined for mandatory property '$($parameter.Key)' and custom role '$CustomRole'" -ErrorAction Stop
                    }
                }

                #test if there are custom role properties defined that do not map to the custom role parameters
                if ($Properties)
                {
                    foreach ($property in $properties.GetEnumerator())
                    {
                        if (-not $scriptInfo.Parameters.ContainsKey($property.Key) -and -not $unknownParameters.Contains($property.Key))
                        {
                            $unknownParameters.Add($property.Key)
                        }
                    }
                }
            }

            #antoher loop is required to remove all unknown parameters that are added due to the order of the first loop
            foreach ($script in $scripts)
            {
                $scriptFullName = Join-Path -Path $activity.DependencyFolder -ChildPath $script
                if (-not (Test-Path -Path $scriptFullName))
                {
                    continue
                }
                $scriptInfo = Get-Command -Name $scriptFullName
                $commonParameters = [System.Management.Automation.Internal.CommonParameters].GetProperties().Name
                $parameters = $scriptInfo.Parameters.GetEnumerator() | Where-Object Key -NotIn $commonParameters

                if ($Properties)
                {
                    foreach ($property in $properties.GetEnumerator())
                    {
                        if ($scriptInfo.Parameters.ContainsKey($property.Key) -and $unknownParameters.Contains($property.Key))
                        {
                            $unknownParameters.Remove($property.Key) | Out-Null
                        }
                    }
                }
            }

            if ($unknownParameters.Count -gt 0)
            {
                Write-Error "The defined properties '$($unknownParameters -join ', ')' are unknown for custom role '$CustomRole'" -ErrorAction Stop
            }

            if ($Properties)
            {
                $activity.SerializedProperties = $Properties | ConvertTo-PSFClixml -ErrorAction SilentlyContinue
            }
        }

        $activity.DoNotUseCredSsp = $DoNotUseCredSsp
    }

    end
    {
        Write-LogFunctionExit -ReturnValue $activity
        return $activity
    }
}
#endregion Get-PostInstallationActivity
#endregion Machine Definition Functions

#region Get-DiskSpeed
function Get-DiskSpeed
{
    [CmdletBinding()]
    param (
        [ValidatePattern('[a-zA-Z]')]
        [Parameter(Mandatory)]
        [string]$DriveLetter,

        [ValidateRange(1, 50)]
        [int]$Interations = 1
    )

    Write-LogFunctionEntry

    if (-not $labSources)
    {
        $labSources = Get-LabSourcesLocation
    }

    $IsReadOnly = Get-Partition -DriveLetter ($DriveLetter.TrimEnd(':')) | Select-Object -ExpandProperty IsReadOnly
    if ($IsReadOnly)
    {
        Write-ScreenInfo -Message "Drive $DriveLetter is read-only. Skipping disk speed test" -Type Warning

        $readThroughoutRandom = 0
        $writeThroughoutRandom = 0
    }
    else
    {
        Write-ScreenInfo -Message "Measuring speed of drive $DriveLetter" -Type Info

        $tempFileName = [System.IO.Path]::GetTempFileName()

        & "$labSources\Tools\WinSAT.exe" disk -ran -read -count $Interations -drive $DriveLetter -xml $tempFileName | Out-Null
        $readThroughoutRandom = (Select-Xml -Path $tempFileName -XPath '/WinSAT/Metrics/DiskMetrics/AvgThroughput').Node.'#text'

        & "$labSources\Tools\WinSAT.exe" disk -ran -write -count $Interations -drive $DriveLetter -xml $tempFileName | Out-Null
        $writeThroughoutRandom = (Select-Xml -Path $tempFileName -XPath '/WinSAT/Metrics/DiskMetrics/AvgThroughput').Node.'#text'

        Remove-Item -Path $tempFileName
    }

    $result = New-Object PSObject -Property ([ordered]@{
            ReadRandom  = $readThroughoutRandom
            WriteRandom = $writeThroughoutRandom
        })

    $result

    Write-LogFunctionExit
}
#endregion

#region Set-LabLocalVirtualMachineDiskAuto
function Set-LabLocalVirtualMachineDiskAuto
{
    [CmdletBinding()]
    param
    (
        [int64]
        $SpaceNeeded
    )

    $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.LocalDisk
    $drives = New-Object $type

    #read the cache
    try
    {
        if ($IsLinux -or $IsMacOs)
        {
            $cachedDrives = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/LocalDisks.xml'))
        }
        else
        {
            $cachedDrives = $type::ImportFromRegistry('Cache', 'LocalDisks')
        }
        Write-PSFMessage "Read $($cachedDrives.Count) drive infos from the cache"
    }
    catch
    {
        Write-PSFMessage 'Could not read info from the cache'
    }

    #Retrieve drives with enough space for placement of VMs
    foreach ($drive in (Get-LabVolumesOnPhysicalDisks | Where-Object FreeSpace -ge $SpaceNeeded))
    {
        $drives.Add($drive)
    }

    if (-not $drives)
    {
        return $false
    }

    #if the current disk config is different from the is in the cache, wait until the running lab deployment is done.
    if ($cachedDrives -and (Compare-Object -ReferenceObject $drives.DriveLetter -DifferenceObject $cachedDrives.DriveLetter))
    {
        $labDiskDeploymentInProgressPath = Get-LabConfigurationItem -Name DiskDeploymentInProgressPath
        if (Test-Path -Path $labDiskDeploymentInProgressPath)
        {
            Write-ScreenInfo "Another lab disk deployment seems to be in progress. If this is not correct, please delete the file '$labDiskDeploymentInProgressPath'." -Type Warning
            Write-ScreenInfo "Waiting with 'Get-DiskSpeed' until other disk deployment is finished. Otherwise a mounted virtual disk could be chosen for deployment." -NoNewLine
            do
            {
                Write-ScreenInfo -Message . -NoNewLine
                Start-Sleep -Seconds 15
            } while (Test-Path -Path $labDiskDeploymentInProgressPath)
        }
        Write-ScreenInfo 'done'

        #refresh the list of drives with enough space for placement of VMs
        $drives.Clear()
        foreach ($drive in (Get-LabVolumesOnPhysicalDisks | Where-Object FreeSpace -ge $SpaceNeeded))
        {
            $drives.Add($drive)
        }

        if (-not $drives)
        {
            return $false
        }
    }

    Write-Debug -Message "Drive letters placed on physical drives: $($drives.DriveLetter -Join ', ')"
    foreach ($drive in $drives)
    {
        Write-Debug -Message "Drive $drive free space: $($drive.FreeSpaceGb)GB)"
    }

    #Measure speed on drives found
    Write-PSFMessage -Message 'Measuring speed on fixed drives...'

    for ($i = 0; $i -lt $drives.Count; $i++)
    {
        $drive = $drives[$i]

        if ($cachedDrives -contains $drive)
        {
            $drive = ($cachedDrives -eq $drive)[0]
            $drives[$drives.IndexOf($drive)] = $drive
            Write-PSFMessage -Message "(cached) Measurements for drive $drive (serial: $($drive.Serial)) (signature: $($drive.Signature)): Read=$([int]($drive.ReadSpeed)) MB/s Write=$([int]($drive.WriteSpeed)) MB/s Total=$([int]($drive.TotalSpeed)) MB/s"
        }
        else
        {
            $result = Get-DiskSpeed -DriveLetter $drive.DriveLetter
            $drive.ReadSpeed = $result.ReadRandom
            $drive.WriteSpeed = $result.WriteRandom

            Write-PSFMessage -Message "Measurements for drive $drive (serial: $($drive.Serial)) (signature: $($drive.Signature)): Read=$([int]($drive.ReadSpeed)) MB/s Write=$([int]($drive.WriteSpeed)) MB/s Total=$([int]($drive.TotalSpeed)) MB/s"
        }
    }

    if ($IsLinux -or $IsMacOs)
    {
        $drives.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/LocalDisks.xml'))
    }
    else
    {
        $drives.ExportToRegistry('Cache', 'LocalDisks')
    }

    #creating a new list is required as otherwise $drives would be converted into an Object[]
    $drives = $drives | Sort-Object -Property TotalSpeed -Descending
    $bootDrive = $drives | Where-Object DriveLetter -eq $env:SystemDrive[0]
    if ($bootDrive)
    {
        Write-PSFMessage -Message "Boot drive is drive '$bootDrive'"
    }
    else
    {
        Write-PSFMessage -Message 'Boot drive is not part of the selected drive'
    }

    if ($drives[0] -ne $bootDrive)
    {
        #Fastest drive is not the boot drive. Selecting this drive!
        Write-PSFMessage -Message "Selecing drive $($drives[0].DriveLetter) for VMs based on speed and NOT being the boot drive"
        $script:lab.Target.Path = "$($drives[0].DriveLetter):\AutomatedLab-VMs"
    }
    else
    {
        if ($drives.Count -lt 2)
        {
            Write-PSFMessage "Selecing drive $($drives[0].DriveLetter) for VMs as it is the only one"
            $script:lab.Target.Path = "$($drives[0].DriveLetter):\AutomatedLab-VMs"
        }
        #Fastest drive is the boot drive. If speed on next fastest drive is close to the boot drive in speed (within 50%), select this drive now instead of the boot drive
        #If not, select the boot drive
        elseif (($drives[1].TotalSpeed * 100 / $drives[0].TotalSpeed) -gt 50)
        {
            Write-PSFMessage "Selecing drive $($drives[1].DriveLetter) for VMs based on speed and NOT being the boot drive"
            Write-PSFMessage "Selected disk speed compared to system disk is $(($drives[1].TotalSpeed * 100 / $drives[0].TotalSpeed))%"

            $script:lab.Target.Path = "$($drives[1].DriveLetter):\AutomatedLab-VMs"
        }
        else
        {
            Write-PSFMessage "Selecing drive $($drives[0].DriveLetter) for VMs based on speed though this drive is actually the boot drive but is much faster than second fastest drive ($($drives[1].DriveLetter))"
            Write-PSFMessage ('Selected system disk, speed of next fastest disk compared to system disk is {0:P}' -f ($drives[1].TotalSpeed / $drives[0].TotalSpeed))
            $script:lab.Target.Path = "$($drives[0].DriveLetter):\AutomatedLab-VMs"
        }
    }
}
#endregion Set-LabLocalVirtualMachineDiskAuto

#region Get-LabVirtualNetwork
function Get-LabVirtualNetwork
{
    [cmdletBinding()]

    $virtualnetworks = @()

    $switches = if ($IsLinux)
    {  
    }
    else
    {
        Get-VMSwitch 
    }

    foreach ($switch in $switches)
    {
        $network = New-Object AutomatedLab.VirtualNetwork
        $network.Name = $switch.Name
        $network.SwitchType = $switch.SwitchType.ToString()
        $ipAddress = Get-NetIPAddress -AddressFamily IPv4 |
        Where-Object { $_.InterfaceAlias -eq "vEthernet ($($network.Name))" -and $_.PrefixOrigin -eq 'manual' } |
        Select-Object -First 1

        if ($ipAddress)
        {
            $network.AddressSpace = "$($ipAddress.IPAddress)/$($ipAddress.PrefixLength)"
        }

        $virtualnetworks += $network
    }

    $virtualnetworks
}
#endregion Get-LabVirtualNetwork

#region Get-LabAvailableAddresseSpace
function Get-LabAvailableAddresseSpace
{
    $defaultAddressSpace = Get-LabConfigurationItem -Name DefaultAddressSpace

    if (-not $defaultAddressSpace)
    {
        Write-Error 'Could not get the PrivateData value DefaultAddressSpace. Cannot find an available address space.'
        return
    }

    $existingHyperVVirtualSwitches = Get-LabVirtualNetwork

    $networkFound = $false
    $addressSpace = [AutomatedLab.IPNetwork]$defaultAddressSpace

    if ($null -eq $reservedAddressSpaces)
    {
        $script:reservedAddressSpaces = @() 
    }

    do
    {
        $addressSpace = $addressSpace.Increment()

        $conflictingSwitch = $existingHyperVVirtualSwitches | Where-Object AddressSpace -eq $addressSpace
        if ($conflictingSwitch)
        {
            Write-PSFMessage -Message "Network '$addressSpace' is in use by existing Hyper-V virtual switch '$conflictingSwitch'"
            continue
        }

        if ($addressSpace -in $reservedAddressSpaces)
        {
            Write-PSFMessage -Message "Network '$addressSpace' has already been defined in this lab"
            continue
        }

        $localAddresses = if ($IsLinux)
        {
            (ip -4 addr) | grep -oP '(?<=inet\s)\d+(\.\d+){3}'
        }
        else
        {
            (Get-NetIPAddress -AddressFamily IPv4).IPAddress
        }

        if ($addressSpace.IpAddress -in $localAddresses)
        {
            Write-PSFMessage -Message "Network '$addressSpace' is in use locally"
            continue
        }

        $route = if ($IsLinux)
        {
            (route | Select-Object -First 5 -Skip 2 | ForEach-Object { '{0}/{1}' -f ($_ -split '\s+')[0], (ConvertTo-MaskLength ($_ -split '\s+')[2]) })
        }
        else
        {
            Get-NetRoute -DestinationPrefix $addressSpace.ToString() -ErrorAction SilentlyContinue
        }

        if ($null -ne $route)
        {
            Write-PSFMessage -Message "Network '$addressSpace' is routable"
            continue
        }

        $networkFound = $true
    }
    until ($networkFound)

    $script:reservedAddressSpaces += $addressSpace
    $addressSpace
}
#endregion Get-LabAvailableAddresseSpace

function Import-LabDefinition
{
    [CmdletBinding(DefaultParameterSetName = 'ByName')]
    param (
        [Parameter(Mandatory, ParameterSetName = 'ByPath', Position = 1)]
        [string]$Path,

        [Parameter(Mandatory, ParameterSetName = 'ByName', Position = 1)]
        [string]$Name,

        [switch]$PassThru
    )

    Write-LogFunctionEntry

    Clear-Lab

    $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Machine
    $script:machines = New-Object $type
    $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Disk
    $script:disks = New-Object $type
    $script:labPath = "$((Get-LabConfigurationItem -Name LabAppDataRoot))/Labs/$Name"
    $machineDefinitionFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem MachineFileName)
    $diskDefinitionFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem DiskFileName)
    $global:labExported = $false

    if ($PSCmdlet.ParameterSetName -in 'ByPath', 'ByName')
    {
        if ($Name)
        {
            $Path = "$((Get-LabConfigurationItem -Name LabAppDataRoot))/Labs/$Name"
        }

        if (Test-Path -Path $Path -PathType Container)
        {
            $newPath = Join-Path -Path $Path -ChildPath Lab.xml
            if (-not (Test-Path -Path $newPath -PathType Leaf))
            {
                throw "The file '$newPath' is missing. Please point to an existing lab file / folder."
            }
            else
            {
                $Path = $newPath
            }
        }
        elseif (Test-Path -Path $Path -PathType Leaf)
        {
            #file is there, do nothing
        }
        else
        {
            throw "The file '$Path' is missing. Please point to an existing lab file / folder."
        }

        if (-not ($IsLinux -or $IsMacOs) -and -not (Test-IsAdministrator))
        {
            throw 'Import-Lab needs to be called in an elevated PowerShell session.'
        }

        if (Test-Path -Path $Path)
        {
            $Script:lab = [AutomatedLab.Lab]::Import((Resolve-Path -Path $Path))

            $Script:lab | Add-Member -MemberType ScriptMethod -Name GetMachineTargetPath -Value {
                param (
                    [string]$MachineName
                )

                (Join-Path -Path $this.Target.Path -ChildPath $MachineName)
            }
        }
        else
        {
            throw 'Lab Definition File not found'
        }

        #import all the machine files referenced in the lab.xml
        $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Machine
        $importMethodInfo = $type.GetMethod('Import',[System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static, [System.Type]::DefaultBinder, [Type[]]@([string]), $null)

        try
        {
            $Script:lab.Machines = $importMethodInfo.Invoke($null, $Script:lab.MachineDefinitionFiles[0].Path)

            if ($Script:lab.MachineDefinitionFiles.Count -gt 1)
            {
                foreach ($machineDefinitionFile in $Script:lab.MachineDefinitionFiles[1..($Script:lab.MachineDefinitionFiles.Count - 1)])
                {
                    $Script:lab.Machines.AddFromFile($machineDefinitionFile.Path)
                }
            }

            if ($Script:lab.Machines)
            {
                $Script:lab.Machines | Add-Member -MemberType ScriptProperty -Name UnattendedXmlContent -Value {
                    if ($this.OperatingSystem.Version -lt '6.2')
                    {
                        $Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath 'Unattended2008.xml'
                    }
                    else
                    {
                        $Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath 'Unattended2012.xml'
                    }
                    if ($this.OperatingSystemType -eq 'Linux' -and $this.LinuxType -eq 'RedHat')
                    {
                        $Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath ks_default.cfg
                    }
                    if ($this.OperatingSystemType -eq 'Linux' -and $this.LinuxType -eq 'Suse')
                    {
                        $Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath autoinst_default.xml
                    }
                    return (Get-Content -Path $Path)
                }
            }
        }
        catch
        {
            Write-Error -Message "No machines imported from file $machineDefinitionFile" -Exception $_.Exception -ErrorAction Stop
        }

        #import all the disk files referenced in the lab.xml
        $type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Disk
        $importMethodInfo = $type.GetMethod('Import',[System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static, [System.Type]::DefaultBinder, [Type[]]@([string]), $null)

        try
        {
            $Script:lab.Disks = $importMethodInfo.Invoke($null, $Script:lab.DiskDefinitionFiles[0].Path)

            if ($Script:lab.DiskDefinitionFiles.Count -gt 1)
            {
                foreach ($diskDefinitionFile in $Script:lab.DiskDefinitionFiles[1..($Script:lab.DiskDefinitionFiles.Count - 1)])
                {
                    $Script:lab.Disks.AddFromFile($diskDefinitionFile.Path)
                }
            }
        }
        catch
        {
            Write-ScreenInfo "No disks imported from file '$diskDefinitionFile': $($_.Exception.Message)" -Type Warning
        }

        if ($Script:lab.VMWareSettings.DataCenterName)
        {
            Add-LabVMWareSettings -DataCenterName $Script:lab.VMWareSettings.DataCenterName `
            -DataStoreName $Script:lab.VMWareSettings.DataStoreName `
            -ResourcePoolName $Script:lab.VMWareSettings.ResourcePoolName `
            -VCenterServerName $Script:lab.VMWareSettings.VCenterServerName `
            -Credential ([System.Management.Automation.PSSerializer]::Deserialize($Script:lab.VMWareSettings.Credential))
        }

        if (-not ($IsLinux -or $IsMacOs) -and (Get-LabConfigurationItem -Name OverridePowerPlan))
        {
            $powerSchemeBackup = (powercfg.exe -GETACTIVESCHEME).Split(':')[1].Trim().Split()[0]
            powercfg.exe -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c
        }
    }
    elseif($PSCmdlet.ParameterSetName -eq 'ByValue')
    {
        $Script:lab = [AutomatedLab.Lab]::Import($LabBytes)
    }

    $script:machines = $script:lab.Machines
    $script:disks = $script:lab.Disks

    if ($PassThru)
    {
        $Script:lab
    }

    Write-LogFunctionExit
}

#region Internal
function Repair-LabDuplicateIpAddresses
{
    [CmdletBinding()]
    param ( )

    foreach ($machine in (Get-LabMachineDefinition))
    {
        foreach ($adapter in $machine.NetworkAdapters)
        {
            foreach ($ipAddress in $adapter.Ipv4Address | Where-Object { $_.IPAddress.IsAutoGenerated })
            {
                $currentIp = $ipAddress
                $otherIps = (Get-LabMachineDefinition | Where-Object Name -ne $machine.Name).NetworkAdapters.IPV4Address

                while ($ipAddress.IpAddress -in $otherIps.IpAddress)
                {
                    $ipAddress.IpAddress = $ipAddress.IpAddress.Increment()
                }

                $adapter.Ipv4Address.Remove($currentIp) | Out-Null
                $adapter.Ipv4Address.Add($ipAddress)
            }
        }
    }
}

function Get-OnlineAdapterHardwareAddress
{
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Special handling for Linux")]
    [OutputType([string[]])]
    [CmdletBinding()]
    param ( )

    if ($IsLinux)
    {
        ip link show up | ForEach-Object { if ($_ -match '(\w{2}:?){6}' -and $Matches.0 -ne '00:00:00:00:00:00')
            {
                $Matches.0
            }
        }
    }
    else
    {
        Get-CimInstance Win32_NetworkAdapter | Where-Object { $_.NetEnabled -and $_.NetConnectionID } | Select-Object -ExpandProperty MacAddress
    }
}
#endregion Internal

if (-not (Test-Path "alias:Get-LabPostInstallationActivity")) { New-Alias -Name Get-LabPostInstallationActivity -Value Get-LabInstallationActivity -Description "Alias so that scripts keep working" }