Convert-WindowsImage.ps1

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

function
Convert-WindowsImage
{
    <#
    .NOTES
        Copyright (c) Microsoft Corporation. All rights reserved.
 
        Use of this sample source code is subject to the terms of the Microsoft
        license agreement under which you licensed this sample source code. If
        you did not accept the terms of the license agreement, you are not
        authorized to use this sample source code. For the terms of the license,
        please see the license agreement between you and Microsoft or, if applicable,
        see the LICENSE.RTF on your install media or the root of your tools installation.
        THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.
 
    .SYNOPSIS
        Creates a bootable VHD(X) based on Windows 7 or Windows 8 installation media.
 
    .DESCRIPTION
        Creates a bootable VHD(X) based on Windows 7 or Windows 8 installation media.
 
    .PARAMETER SourcePath
        The complete path to the WIM or ISO file that will be converted to a Virtual Hard Disk.
        The ISO file must be valid Windows installation media to be recognized successfully.
 
    .PARAMETER CacheSource
        If the source WIM/ISO was copied locally, we delete it by default.
        Pass $true to cache the source image from the temp directory.
 
    .PARAMETER VHDPath
        The name and path of the Virtual Hard Disk to create.
        Omitting this parameter will create the Virtual Hard Disk is the current directory, (or,
        if specified by the -WorkingDirectory parameter, the working directory) and will automatically
        name the file in the following format:
 
        <build>.<revision>.<architecture>.<branch>.<timestamp>_<skufamily>_<sku>_<language>.<extension>
        i.e.:
        9200.0.amd64fre.winmain_win8rtm.120725-1247_client_professional_en-us.vhd(x)
 
    .PARAMETER WorkingDirectory
        Specifies the directory where the VHD(X) file should be generated.
        If specified along with -VHDPath, the -WorkingDirectory value is ignored.
        The default value is the current directory ($pwd).
 
    .PARAMETER TempDirectory
        Specifies the directory where the logs and ISO files should be placed.
        The default value is the temp directory ($env:Temp).
 
    .PARAMETER SizeBytes
        The size of the Virtual Hard Disk to create.
        For fixed disks, the VHD(X) file will be allocated all of this space immediately.
        For dynamic disks, this will be the maximum size that the VHD(X) can grow to.
        The default value is 40GB.
 
    .PARAMETER VHDFormat
        Specifies whether to create a VHD or VHDX formatted Virtual Hard Disk.
        The default is AUTO, which will create a VHD if using the BIOS disk layout or
        VHDX if using UEFI or WindowsToGo layouts.
 
    .PARAMETER DiskLayout
        Specifies whether to build the image for BIOS (MBR), UEFI (GPT), or WindowsToGo (MBR).
        Generation 1 VMs require BIOS (MBR) images. Generation 2 VMs require UEFI (GPT) images.
        Windows To Go images will boot in UEFI or BIOS but are not technically supported (upgrade
        doesn't work)
 
    .PARAMETER UnattendPath
        The complete path to an unattend.xml file that can be injected into the VHD(X).
 
    .PARAMETER Edition
        The name or image index of the image to apply from the WIM.
 
    .PARAMETER Passthru
        Specifies that the full path to the VHD(X) that is created should be
        returned on the pipeline.
 
    .PARAMETER BCDBoot
        By default, the version of BCDBOOT.EXE that is present in \Windows\System32
        is used by Convert-WindowsImage. If you need to specify an alternate version,
        use this parameter to do so.
 
    .PARAMETER MergeFolder
        Specifies additional MergeFolder path to be added to the root of the VHD(X)
 
    .PARAMETER BCDinVHD
        Specifies the purpose of the VHD(x). Use NativeBoot to skip cration of BCD store
        inside the VHD(x). Use VirtualMachine (or do not specify this option) to ensure
        the BCD store is created inside the VHD(x).
 
    .PARAMETER Driver
        Full path to driver(s) (.inf files) to inject to the OS inside the VHD(x).
 
    .PARAMETER ExpandOnNativeBoot
        Specifies whether to expand the VHD(x) to its maximum suze upon native boot.
        The default is True. Set to False to disable expansion.
 
    .PARAMETER RemoteDesktopEnable
        Enable Remote Desktop to connect to the OS inside the VHD(x) upon provisioning.
        Does not include Windows Firewall rules (firewall exceptions). The default is False.
 
    .PARAMETER Feature
        Enables specified Windows Feature(s). Note that you need to specify the Internal names
        understood by DISM and DISM CMDLets (e.g. NetFx3) instead of the "Friendly" names
        from Server Manager CMDLets (e.g. NET-Framework-Core).
 
    .PARAMETER Package
        Injects specified Windows Package(s). Accepts path to either a directory or individual
        CAB or MSU file.
 
    .PARAMETER ShowUI
        Specifies that the Graphical User Interface should be displayed.
 
    .PARAMETER EnableDebugger
        Configures kernel debugging for the VHD(X) being created.
        EnableDebugger takes a single argument which specifies the debugging transport to use.
        Valid transports are: None, Serial, 1394, USB, Network, Local.
 
        Depending on the type of transport selected, additional configuration parameters will become
        available.
 
        Serial:
            -ComPort - The COM port number to use while communicating with the debugger.
                         The default value is 1 (indicating COM1).
            -BaudRate - The baud rate (in bps) to use while communicating with the debugger.
                         The default value is 115200, valid values are:
                         9600, 19200, 38400, 56700, 115200
 
        1394:
            -Channel - The 1394 channel used to communicate with the debugger.
                         The default value is 10.
 
        USB:
            -Target - The target name used for USB debugging.
                         The default value is "debugging".
 
        Network:
            -IPAddress - The IP address of the debugging host computer.
            -Port - The port on which to connect to the debugging host.
                         The default value is 50000, with a minimum value of 49152.
            -Key - The key used to encrypt the connection. Only [0-9] and [a-z] are allowed.
            -nodhcp - Prevents the use of DHCP to obtain the target IP address.
            -newkey - Specifies that a new encryption key should be generated for the connection.
 
    .PARAMETER DismPath
        Full Path to an alternative version of the Dism.exe tool. The default is the current OS version.
 
    .PARAMETER ApplyEA
        Specifies that any EAs captured in the WIM should be applied to the VHD.
        The default is False.
 
    .EXAMPLE
        .\Convert-WindowsImage.ps1 -SourcePath D:\foo\install.wim -Edition Professional -WorkingDirectory D:\foo
 
        This command will create a 40GB dynamically expanding VHD in the D:\foo folder.
        The VHD will be based on the Professional edition from D:\foo\install.wim,
        and will be named automatically.
 
    .EXAMPLE
        .\Convert-WindowsImage.ps1 -SourcePath D:\foo\Win7SP1.iso -Edition Ultimate -VHDPath D:\foo\Win7_Ultimate_SP1.vhd
 
        This command will parse the ISO file D:\foo\Win7SP1.iso and try to locate
        \sources\install.wim. If that file is found, it will be used to create a
        dynamically-expanding 40GB VHD containing the Ultimate SKU, and will be
        named D:\foo\Win7_Ultimate_SP1.vhd
 
    .EXAMPLE
        .\Convert-WindowsImage.ps1 -SourcePath D:\foo\install.wim -Edition Professional -EnableDebugger Serial -ComPort 2 -BaudRate 38400
 
        This command will create a VHD from D:\foo\install.wim of the Professional SKU.
        Serial debugging will be enabled in the VHD via COM2 at a baud rate of 38400bps.
 
    .OUTPUTS
        System.IO.FileInfo
    #>

    #Requires -Version 3.0
    [CmdletBinding(DefaultParameterSetName="SRC",
        HelpURI="https://github.com/Microsoft/Virtualization-Documentation/tree/master/hyperv-tools/Convert-WindowsImage")]

    param(
        [Parameter(ParameterSetName="SRC", Mandatory=$true, ValueFromPipeline=$true)]
        [Alias("WIM")]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({ Test-Path $(Resolve-Path $_) })]
        $SourcePath,

        [Parameter(ParameterSetName="SRC")]
        [switch]
        $CacheSource = $false,

        [Parameter(ParameterSetName="SRC")]
        [Alias("SKU")]
        [string[]]
        [ValidateNotNullOrEmpty()]
        $Edition,

        [Parameter(ParameterSetName="SRC")]
        [Alias("WorkDir")]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({ Test-Path $_ })]
        $WorkingDirectory = $pwd,

        [Parameter(ParameterSetName="SRC")]
        [Alias("TempDir")]
        [string]
        [ValidateNotNullOrEmpty()]
        $TempDirectory = $env:Temp,

        [Parameter(ParameterSetName="SRC")]
        [Alias("VHD")]
        [string]
        [ValidateNotNullOrEmpty()]
        $VHDPath,

        [Parameter(ParameterSetName="SRC")]
        [Alias("Size")]
        [UInt64]
        [ValidateNotNullOrEmpty()]
        [ValidateRange(512MB, 64TB)]
        $SizeBytes = 25GB,

        [Parameter(ParameterSetName="SRC")]
        [Alias("Format")]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet("VHD", "VHDX", "AUTO")]
        $VHDFormat = "AUTO",

        [Parameter(ParameterSetName="SRC")]
        [Alias("MergeFolder")]
        [string]
        [ValidateNotNullOrEmpty()]
        $MergeFolderPath = "",

        [Parameter(ParameterSetName="SRC", Mandatory=$true)]
        [Alias("Layout")]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet("BIOS", "UEFI", "WindowsToGo")]
        $DiskLayout,

        [Parameter(ParameterSetName="SRC")]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet("NativeBoot", "VirtualMachine")]
        $BCDinVHD = "VirtualMachine",

        [Parameter(ParameterSetName="SRC")]
        [Parameter(ParameterSetName="UI")]
        [string]
        $BCDBoot = "bcdboot.exe",

        [Parameter(ParameterSetName="SRC")]
        [Parameter(ParameterSetName="UI")]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet("None", "Serial", "1394", "USB", "Local", "Network")]
        $EnableDebugger = "None",

        [Parameter(ParameterSetName="SRC")]
        [string[]]
        [ValidateNotNullOrEmpty()]
        $Feature,

        [Parameter(ParameterSetName="SRC")]
        [string[]]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({ Test-Path $(Resolve-Path $_) })]
        $Driver,

        [Parameter(ParameterSetName="SRC")]
        [string[]]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({ Test-Path $(Resolve-Path $_) })]
        $Package,

        [Parameter(ParameterSetName="SRC")]
        [switch]
        $ExpandOnNativeBoot = $true,

        [Parameter(ParameterSetName="SRC")]
        [switch]
        $RemoteDesktopEnable = $false,

        [Parameter(ParameterSetName="SRC")]
        [Alias("Unattend")]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({ Test-Path $(Resolve-Path $_) })]
        $UnattendPath,

        [Parameter(ParameterSetName="SRC")]
        [Parameter(ParameterSetName="UI")]
        [switch]
        $Passthru,

        [Parameter(ParameterSetName="SRC")]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({ Test-Path $(Resolve-Path $_) })]
        $DismPath,

        [Parameter(ParameterSetName="SRC")]
        [switch]
        $ApplyEA = $false,

        [Parameter(ParameterSetName="UI")]
        [switch]
        $ShowUI
    )
    #region Code

    # Begin Dynamic Parameters
    # Create the parameters for the various types of debugging.
    DynamicParam
    {
        Set-StrictMode -version 3

        # Set up the dynamic parameters.
        # Dynamic parameters are only available if certain conditions are met, so they'll only show up
        # as valid parameters when those conditions apply. Here, the conditions are based on the value of
        # the EnableDebugger parameter. Depending on which of a set of values is the specified argument
        # for EnableDebugger, different parameters will light up, as outlined below.

        $parameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

        if (!(Test-Path Variable:Private:EnableDebugger))
        {
            return $parameterDictionary
        }

        switch ($EnableDebugger)
        {
            "Serial"
            {
                #region ComPort

                $ComPortAttr                   = New-Object System.Management.Automation.ParameterAttribute
                $ComPortAttr.ParameterSetName  = "__AllParameterSets"
                $ComPortAttr.Mandatory         = $false

                $ComPortValidator              = New-Object System.Management.Automation.ValidateRangeAttribute(
                                                    1,
                                                    10   # Is that a good maximum?
                                                 )

                $ComPortNotNull                = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute

                $ComPortAttrCollection         = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $ComPortAttrCollection.Add($ComPortAttr)
                $ComPortAttrCollection.Add($ComPortValidator)
                $ComPortAttrCollection.Add($ComPortNotNull)

                $ComPort                       = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                    "ComPort",
                                                    [UInt16],
                                                    $ComPortAttrCollection
                                                 )

                # By default, use COM1
                $ComPort.Value                 = 1
                $parameterDictionary.Add("ComPort", $ComPort)
                #endregion ComPort

                #region BaudRate
                $BaudRateAttr                  = New-Object System.Management.Automation.ParameterAttribute
                $BaudRateAttr.ParameterSetName = "__AllParameterSets"
                $BaudRateAttr.Mandatory        = $false

                $BaudRateValidator             = New-Object System.Management.Automation.ValidateSetAttribute(
                                                    9600, 19200,38400, 57600, 115200
                                                 )

                $BaudRateNotNull               = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute

                $BaudRateAttrCollection        = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $BaudRateAttrCollection.Add($BaudRateAttr)
                $BaudRateAttrCollection.Add($BaudRateValidator)
                $BaudRateAttrCollection.Add($BaudRateNotNull)

                $BaudRate                      = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                     "BaudRate",
                                                     [UInt32],
                                                     $BaudRateAttrCollection
                                                 )

                # By default, use 115,200.
                $BaudRate.Value                = 115200
                $parameterDictionary.Add("BaudRate", $BaudRate)
                #endregion BaudRate

                break
            }

            "1394"
            {
                $ChannelAttr                   = New-Object System.Management.Automation.ParameterAttribute
                $ChannelAttr.ParameterSetName  = "__AllParameterSets"
                $ChannelAttr.Mandatory         = $false

                $ChannelValidator              = New-Object System.Management.Automation.ValidateRangeAttribute(
                                                    0,
                                                    62
                                                 )

                $ChannelNotNull                = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute

                $ChannelAttrCollection         = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $ChannelAttrCollection.Add($ChannelAttr)
                $ChannelAttrCollection.Add($ChannelValidator)
                $ChannelAttrCollection.Add($ChannelNotNull)

                $Channel                       = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                     "Channel",
                                                     [UInt16],
                                                     $ChannelAttrCollection
                                                 )

                # By default, use channel 10
                $Channel.Value                 = 10
                $parameterDictionary.Add("Channel", $Channel)
                break
            }

            "USB"
            {
                $TargetAttr                    = New-Object System.Management.Automation.ParameterAttribute
                $TargetAttr.ParameterSetName   = "__AllParameterSets"
                $TargetAttr.Mandatory          = $false

                $TargetNotNull                 = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute

                $TargetAttrCollection          = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $TargetAttrCollection.Add($TargetAttr)
                $TargetAttrCollection.Add($TargetNotNull)

                $Target                        = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                     "Target",
                                                     [string],
                                                     $TargetAttrCollection
                                                 )

                # By default, use target = "debugging"
                $Target.Value                  = "Debugging"
                $parameterDictionary.Add("Target", $Target)
                break
            }

            "Network"
            {
                #region IP
                $IpAttr                        = New-Object System.Management.Automation.ParameterAttribute
                $IpAttr.ParameterSetName       = "__AllParameterSets"
                $IpAttr.Mandatory              = $true

                $IpValidator                   = New-Object System.Management.Automation.ValidatePatternAttribute(
                                                    "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
                                                 )
                $IpNotNull                     = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute

                $IpAttrCollection              = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $IpAttrCollection.Add($IpAttr)
                $IpAttrCollection.Add($IpValidator)
                $IpAttrCollection.Add($IpNotNull)

                $IP                            = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                     "IPAddress",
                                                     [string],
                                                     $IpAttrCollection
                                                 )

                # There's no good way to set a default value for this.
                $parameterDictionary.Add("IPAddress", $IP)
                #endregion IP

                #region Port
                $PortAttr                      = New-Object System.Management.Automation.ParameterAttribute
                $PortAttr.ParameterSetName     = "__AllParameterSets"
                $PortAttr.Mandatory            = $false

                $PortValidator                 = New-Object System.Management.Automation.ValidateRangeAttribute(
                                                    49152,
                                                    50039
                                                 )

                $PortNotNull                   = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute

                $PortAttrCollection            = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $PortAttrCollection.Add($PortAttr)
                $PortAttrCollection.Add($PortValidator)
                $PortAttrCollection.Add($PortNotNull)


                $Port                          = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                     "Port",
                                                     [UInt16],
                                                     $PortAttrCollection
                                                 )

                # By default, use port 50000
                $Port.Value                    = 50000
                $parameterDictionary.Add("Port", $Port)
                #endregion Port

                #region Key
                $KeyAttr                       = New-Object System.Management.Automation.ParameterAttribute
                $KeyAttr.ParameterSetName      = "__AllParameterSets"
                $KeyAttr.Mandatory             = $true

                $KeyValidator                  = New-Object System.Management.Automation.ValidatePatternAttribute(
                                                    "\b([A-Z0-9]+).([A-Z0-9]+).([A-Z0-9]+).([A-Z0-9]+)\b"
                                                 )

                $KeyNotNull                    = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute

                $KeyAttrCollection             = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $KeyAttrCollection.Add($KeyAttr)
                $KeyAttrCollection.Add($KeyValidator)
                $KeyAttrCollection.Add($KeyNotNull)

                $Key                           = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                     "Key",
                                                     [string],
                                                     $KeyAttrCollection
                                                 )

                # Don't set a default key.
                $parameterDictionary.Add("Key", $Key)
                #endregion Key

                #region NoDHCP
                $NoDHCPAttr                    = New-Object System.Management.Automation.ParameterAttribute
                $NoDHCPAttr.ParameterSetName   = "__AllParameterSets"
                $NoDHCPAttr.Mandatory          = $false

                $NoDHCPAttrCollection          = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $NoDHCPAttrCollection.Add($NoDHCPAttr)

                $NoDHCP                        = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                     "NoDHCP",
                                                     [switch],
                                                     $NoDHCPAttrCollection
                                                 )

                $parameterDictionary.Add("NoDHCP", $NoDHCP)
                #endregion NoDHCP

                #region NewKey
                $NewKeyAttr                    = New-Object System.Management.Automation.ParameterAttribute
                $NewKeyAttr.ParameterSetName   = "__AllParameterSets"
                $NewKeyAttr.Mandatory          = $false

                $NewKeyAttrCollection          = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
                $NewKeyAttrCollection.Add($NewKeyAttr)

                $NewKey                        = New-Object System.Management.Automation.RuntimeDefinedParameter(
                                                     "NewKey",
                                                     [switch],
                                                     $NewKeyAttrCollection
                                                 )

                # Don't set a default key.
                $parameterDictionary.Add("NewKey", $NewKey)
                #endregion NewKey

                break
            }

            # There's nothing to do for local debugging.
            # Synthetic debugging is not yet implemented.

            default
            {
               break
            }
        }

        return $parameterDictionary
    }

    Begin
    {
        ##########################################################################################
        # Constants and Pseudo-Constants
        ##########################################################################################
        $PARTITION_STYLE_MBR    = 0x00000000                                   # The default value
        $PARTITION_STYLE_GPT    = 0x00000001                                   # Just in case...

        # Version information that can be populated by timebuild.
        $ScriptVersion = DATA
        {
    ConvertFrom-StringData -StringData @"
        Major = 10
        Minor = 0
        Build = 14278
        Qfe = 1000
        Branch = rs1_es_media
        Timestamp = 160201-1707
        Flavor = amd64fre
"@

}

        $myVersion              = "$($ScriptVersion.Major).$($ScriptVersion.Minor).$($ScriptVersion.Build).$($ScriptVersion.QFE).$($ScriptVersion.Flavor).$($ScriptVersion.Branch).$($ScriptVersion.Timestamp)"
        $scriptName             = "Convert-WindowsImage"                       # Name of the script, obviously.
        $sessionKey             = [Guid]::NewGuid().ToString()                 # Session key, used for keeping records unique between multiple runs.
        $logFolder              = "$($TempDirectory)\$($scriptName)\$($sessionKey)" # Log folder path.
        $vhdMaxSize             = 2040GB                                       # Maximum size for VHD is ~2040GB.
        $vhdxMaxSize            = 64TB                                         # Maximum size for VHDX is ~64TB.
        $lowestSupportedVersion = New-Object Version "6.1"                     # The lowest supported *image* version; making sure we don't run against Vista/2k8.
        $lowestSupportedBuild   = 9200                                         # The lowest supported *host* build. Set to Win8 CP.
        $transcripting          = $false

        # Since we use the VHDFormat in output, make it uppercase.
        # We'll make it lowercase again when we use it as a file extension.
        $VHDFormat              = $VHDFormat.ToUpper()
        ##########################################################################################
        # Here Strings
        ##########################################################################################

        # Banner text displayed during each run.
        $header    = @"
 
Windows(R) Image to Virtual Hard Disk Converter for Windows(R) 10
Copyright (C) Microsoft Corporation. All rights reserved.
Version $myVersion
 
"@


        # Text used as the banner in the UI.
        $uiHeader  = @"
You can use the fields below to configure the VHD or VHDX that you want to create!
"@


        #region Helper Functions

        ##########################################################################################
        # Helper Functions
        ##########################################################################################

        <#
            Functions to mount and dismount registry hives.
            These hives will automatically be accessible via the HKLM:\ registry PSDrive.
 
            It should be noted that I have more confidence in using the RegLoadKey and
            RegUnloadKey Win32 APIs than I do using REG.EXE - it just seems like we should
            do things ourselves if we can, instead of using yet another binary.
 
            Consider this a TODO for future versions.
        #>

        Function Mount-RegistryHive
        {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
                [System.IO.FileInfo]
                [ValidateNotNullOrEmpty()]
                [ValidateScript({ $_.Exists })]
                $Hive
            )

            $mountKey = [System.Guid]::NewGuid().ToString()
            $regPath  = "REG.EXE"

            if (Test-Path HKLM:\$mountKey)
            {
                throw "The registry path already exists. I should just regenerate it, but I'm lazy."
            }

            $regArgs = (
                "LOAD",
                "HKLM\$mountKey",
                $Hive.Fullname
            )
            try
            {

                Run-Executable -Executable $regPath -Arguments $regArgs

            }
            catch
            {
                throw
            }

            # Set a global variable containing the name of the mounted registry key
            # so we can unmount it if there's an error.
            $global:mountedHive = $mountKey

            return $mountKey
        }

        ##########################################################################################

        Function Dismount-RegistryHive
        {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
                [string]
                [ValidateNotNullOrEmpty()]
                $HiveMountPoint
            )

            $regPath = "REG.EXE"

            $regArgs = (
                "UNLOAD",
                "HKLM\$($HiveMountPoint)"
            )

            Run-Executable -Executable $regPath -Arguments $regArgs

            $global:mountedHive = $null
        }

        ##########################################################################################

        function
        Test-Admin
        {
            <#
                .SYNOPSIS
                    Short function to determine whether the logged-on user is an administrator.
 
                .EXAMPLE
                    Do you honestly need one? There are no parameters!
 
                .OUTPUTS
                    $true if user is admin.
                    $false if user is not an admin.
            #>

            [CmdletBinding()]
            param()

            $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
            $isAdmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
            Write-W2VTrace "isUserAdmin? $isAdmin"

            return $isAdmin
        }

        ##########################################################################################

        function
        Get-WindowsBuildNumber
        {
            $os = Get-WmiObject -Class Win32_OperatingSystem
            return [int]($os.BuildNumber)
        }

        ##########################################################################################

        function
        Test-WindowsVersion
        {
            $isWin8 = ((Get-WindowsBuildNumber) -ge [int]$lowestSupportedBuild)

            Write-W2VTrace "is Windows 8 or Higher? $isWin8"
            return $isWin8
        }

        ##########################################################################################

        function
        Write-W2VInfo
        {
        # Function to make the Write-Host output a bit prettier.
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
                [string]
                [ValidateNotNullOrEmpty()]
                $text
            )
            Write-Host "INFO : $($text)"
        }

        ##########################################################################################

        function
        Write-W2VTrace
        {
        # Function to make the Write-Verbose output... well... exactly the same as it was before.
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
                [string]
                [ValidateNotNullOrEmpty()]
                $text
            )
            Write-Verbose $text
        }

        ##########################################################################################

        function
        Write-W2VError
        {
        # Function to make the Write-Host (NOT Write-Error) output prettier in the case of an error.
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
                [string]
                [ValidateNotNullOrEmpty()]
                $text
            )
            Write-Host "ERROR : $($text)" -ForegroundColor (Get-Host).PrivateData.ErrorForegroundColor
        }

        ##########################################################################################

        function
        Write-W2VWarn
        {
        # Function to make the Write-Host (NOT Write-Warning) output prettier.
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
                [string]
                [ValidateNotNullOrEmpty()]
                $text
            )
            Write-Host "WARN : $($text)" -ForegroundColor (Get-Host).PrivateData.WarningForegroundColor
        }

        ##########################################################################################

        function
        Run-Executable
        {
            <#
                .SYNOPSIS
                    Runs an external executable file, and validates the error level.
 
                .PARAMETER Executable
                    The path to the executable to run and monitor.
 
                .PARAMETER Arguments
                    An array of arguments to pass to the executable when it's executed.
 
                .PARAMETER SuccessfulErrorCode
                    The error code that means the executable ran successfully.
                    The default value is 0.
            #>


            [CmdletBinding()]
            param(
                [Parameter(Mandatory=$true)]
                [string]
                [ValidateNotNullOrEmpty()]
                $Executable,

                [Parameter(Mandatory=$true)]
                [string[]]
                [ValidateNotNullOrEmpty()]
                $Arguments,

                [Parameter()]
                [int]
                [ValidateNotNullOrEmpty()]
                $SuccessfulErrorCode = 0

            )

            Write-W2VTrace "Running $Executable $Arguments"
            $ret = Start-Process           `
                -FilePath $Executable      `
                -ArgumentList $Arguments   `
                -NoNewWindow               `
                -Wait                      `
                -RedirectStandardOutput "$($TempDirectory)\$($scriptName)\$($sessionKey)\$($Executable)-StandardOutput.txt" `
                -RedirectStandardError  "$($TempDirectory)\$($scriptName)\$($sessionKey)\$($Executable)-StandardError.txt"  `
                -Passthru

            Write-W2VTrace "Return code was $($ret.ExitCode)."

            if ($ret.ExitCode -ne $SuccessfulErrorCode)
            {
                throw "$Executable failed with code $($ret.ExitCode)!"
            }
        }

        ##########################################################################################
        Function Test-IsNetworkLocation
        {
            <#
                .SYNOPSIS
                    Determines whether or not a given path is a network location or a local drive.
 
                .DESCRIPTION
                    Function to determine whether or not a specified path is a local path, a UNC path,
                    or a mapped network drive.
 
                .PARAMETER Path
                    The path that we need to figure stuff out about,
            #>


            [CmdletBinding()]
            param(
                [Parameter(ValueFromPipeLine = $true)]
                [string]
                [ValidateNotNullOrEmpty()]
                $Path
            )

            $result = $false

            if ([bool]([URI]$Path).IsUNC)
            {
                $result = $true
            }
            else
            {
                $driveInfo = [IO.DriveInfo]((Resolve-Path $Path).Path)

                if ($driveInfo.DriveType -eq "Network")
                {
                    $result = $true
                }
            }

            return $result
        }
        ##########################################################################################

        #endregion Helper Functions
    }

    Process
    {
        Write-Host $header
        
        $disk           = $null
        $openWim        = $null
        $openIso        = $null
        $openImage      = $null
        $vhdFinalName   = $null
        $vhdFinalPath   = $null
        $mountedHive    = $null
        $isoPath        = $null
        $tempSource     = $null

        if (Get-Command Get-WindowsOptionalFeature -ErrorAction SilentlyContinue)
        {
            try
            {
                $hyperVEnabled  = $((Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V).State -eq "Enabled")
            }
            catch
            {
                # WinPE DISM does not support online queries. This will throw on non-WinPE machines
                $winpeVersion = (Get-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\WinPE').Version

                Write-W2VInfo "Running WinPE version $winpeVersion"

                $hyperVEnabled = $false
            }
        }
        else
        {
            $hyperVEnabled = $false
        }

        $vhd            = @()

        try
        {
            # Create log folder
            if (Test-Path $logFolder)
            {
                $null = rd $logFolder -Force -Recurse
            }

            $null = md $logFolder -Force

            # Try to start transcripting. If it's already running, we'll get an exception and swallow it.
            try
            {
                $null = Start-Transcript -Path (Join-Path $logFolder "Convert-WindowsImageTranscript.txt") -Force -ErrorAction SilentlyContinue
                $transcripting = $true
            }
            catch
            {
                Write-W2VWarn "Transcription is already running. No Convert-WindowsImage-specific transcript will be created."
                $transcripting = $false
            }

            #
            # Add types
            #
            Add-WindowsImageTypes

            # Check to make sure we're running as Admin.
            if (!(Test-Admin))
            {
                throw "Images can only be applied by an administrator. Please launch PowerShell elevated and run this script again."
            }

            # Check to make sure we're running on Win8.
            if (!(Test-WindowsVersion))
            {
                throw "$scriptName requires Windows 8 Consumer Preview or higher. Please use WIM2VHD.WSF (http://code.msdn.microsoft.com/wim2vhd) if you need to create VHDs from Windows 7."
            }

            # Resolve the path for the unattend file.
            if (![string]::IsNullOrEmpty($UnattendPath))
            {
                $UnattendPath = (Resolve-Path $UnattendPath).Path
            }

            if ($ShowUI)
            {

                Write-W2VInfo "Launching UI..."
                Add-Type -AssemblyName System.Drawing,System.Windows.Forms

                #region Form Objects
                $frmMain                = New-Object System.Windows.Forms.Form
                $groupBox4              = New-Object System.Windows.Forms.GroupBox
                $btnGo                  = New-Object System.Windows.Forms.Button
                $groupBox3              = New-Object System.Windows.Forms.GroupBox
                $txtVhdName             = New-Object System.Windows.Forms.TextBox
                $label6                 = New-Object System.Windows.Forms.Label
                $btnWrkBrowse           = New-Object System.Windows.Forms.Button
                $cmbVhdSizeUnit         = New-Object System.Windows.Forms.ComboBox
                $numVhdSize             = New-Object System.Windows.Forms.NumericUpDown
                $cmbVhdFormat           = New-Object System.Windows.Forms.ComboBox
                $label5                 = New-Object System.Windows.Forms.Label
                $txtWorkingDirectory    = New-Object System.Windows.Forms.TextBox
                $label4                 = New-Object System.Windows.Forms.Label
                $label3                 = New-Object System.Windows.Forms.Label
                $label2                 = New-Object System.Windows.Forms.Label
                $label7                 = New-Object System.Windows.Forms.Label
                $txtUnattendFile        = New-Object System.Windows.Forms.TextBox
                $btnUnattendBrowse      = New-Object System.Windows.Forms.Button
                $groupBox2              = New-Object System.Windows.Forms.GroupBox
                $cmbSkuList             = New-Object System.Windows.Forms.ComboBox
                $label1                 = New-Object System.Windows.Forms.Label
                $groupBox1              = New-Object System.Windows.Forms.GroupBox
                $txtSourcePath          = New-Object System.Windows.Forms.TextBox
                $btnBrowseWim           = New-Object System.Windows.Forms.Button
                $openFileDialog1        = New-Object System.Windows.Forms.OpenFileDialog
                $openFolderDialog1      = New-Object System.Windows.Forms.FolderBrowserDialog
                $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState

                #endregion Form Objects

                #region Event scriptblocks.

                $btnGo_OnClick                          = {
                    $frmMain.Close()
                }

                $btnWrkBrowse_OnClick                   = {
                    $openFolderDialog1.RootFolder       = "Desktop"
                    $openFolderDialog1.Description      = "Select the folder you'd like your VHD(X) to be created in."
                    $openFolderDialog1.SelectedPath     = $WorkingDirectory

                    $ret = $openFolderDialog1.ShowDialog()

                    if ($ret -ilike "ok")
                    {
                        $WorkingDirectory = $txtWorkingDirectory = $openFolderDialog1.SelectedPath
                        Write-W2VInfo "Selected Working Directory is $WorkingDirectory..."
                    }
                }

                $btnUnattendBrowse_OnClick              = {
                    $openFileDialog1.InitialDirectory   = $pwd
                    $openFileDialog1.Filter             = "XML files (*.xml)|*.XML|All files (*.*)|*.*"
                    $openFileDialog1.FilterIndex        = 1
                    $openFileDialog1.CheckFileExists    = $true
                    $openFileDialog1.CheckPathExists    = $true
                    $openFileDialog1.FileName           = $null
                    $openFileDialog1.ShowHelp           = $false
                    $openFileDialog1.Title              = "Select an unattend file..."

                    $ret = $openFileDialog1.ShowDialog()

                    if ($ret -ilike "ok")
                    {
                        $UnattendPath = $txtUnattendFile.Text = $openFileDialog1.FileName
                    }
                }

                $btnBrowseWim_OnClick                   = {
                    $openFileDialog1.InitialDirectory   = $pwd
                    $openFileDialog1.Filter             = "All compatible files (*.ISO, *.WIM)|*.ISO;*.WIM|All files (*.*)|*.*"
                    $openFileDialog1.FilterIndex        = 1
                    $openFileDialog1.CheckFileExists    = $true
                    $openFileDialog1.CheckPathExists    = $true
                    $openFileDialog1.FileName           = $null
                    $openFileDialog1.ShowHelp           = $false
                    $openFileDialog1.Title              = "Select a source file..."

                    $ret = $openFileDialog1.ShowDialog()

                    if ($ret -ilike "ok")
                    {

                        if (([IO.FileInfo]$openFileDialog1.FileName).Extension -ilike ".iso")
                        {

                            if (Test-IsNetworkLocation $openFileDialog1.FileName)
                            {
                                Write-W2VInfo "Copying ISO $(Split-Path $openFileDialog1.FileName -Leaf) to temp folder..."
                                Write-W2VWarn "The UI may become non-responsive while this copy takes place..."
                                Copy-Item -Path $openFileDialog1.FileName -Destination $TempDirectory -Force
                                $openFileDialog1.FileName = "$($TempDirectory)\$(Split-Path $openFileDialog1.FileName -Leaf)"
                            }

                            $txtSourcePath.Text = $isoPath = (Resolve-Path $openFileDialog1.FileName).Path
                            Write-W2VInfo "Opening ISO $(Split-Path $isoPath -Leaf)..."

                            $openIso     = Mount-DiskImage -ImagePath $isoPath -StorageType ISO -PassThru

                            # Refresh the DiskImage object so we can get the real information about it. I assume this is a bug.
                            $openIso     = Get-DiskImage -ImagePath $isoPath
                            $driveLetter = ($openIso | Get-Volume).DriveLetter

                            $script:SourcePath  = "$($driveLetter):\sources\install.wim"

                            # Check to see if there's a WIM file we can muck about with.
                            Write-W2VInfo "Looking for $($SourcePath)..."
                            if (!(Test-Path $SourcePath))
                            {
                                throw "The specified ISO does not appear to be valid Windows installation media."
                            }
                        }
                        else
                        {
                            $txtSourcePath.Text = $script:SourcePath = $openFileDialog1.FileName
                        }

                        # Check to see if the WIM is local, or on a network location. If the latter, copy it locally.
                        if (Test-IsNetworkLocation $SourcePath)
                        {
                            Write-W2VInfo "Copying WIM $(Split-Path $SourcePath -Leaf) to temp folder..."
                            Write-W2VWarn "The UI may become non-responsive while this copy takes place..."
                            Copy-Item -Path $SourcePath -Destination $TempDirectory -Force
                            $txtSourcePath.Text = $script:SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)"
                        }

                        $script:SourcePath = (Resolve-Path $SourcePath).Path

                        Write-W2VInfo "Scanning WIM metadata..."

                        $tempOpenWim = $null

                        try
                        {
                            $tempOpenWim   = New-Object WIM2VHD.WimFile $SourcePath

                            # Let's see if we're running against an unstaged build. If we are, we need to blow up.
                            if ($tempOpenWim.ImageNames.Contains("Windows Longhorn Client") -or
                                $tempOpenWim.ImageNames.Contains("Windows Longhorn Server") -or
                                $tempOpenWim.ImageNames.Contains("Windows Longhorn Server Core"))
                            {
                                [Windows.Forms.MessageBox]::Show(
                                    "Convert-WindowsImage cannot run against unstaged builds. Please try again with a staged build.",
                                    "WIM is incompatible!",
                                    "OK",
                                    "Error"
                                )

                                return
                            }
                            else
                            {
                                $tempOpenWim.Images | %{ $cmbSkuList.Items.Add($_.ImageFlags) }
                                $cmbSkuList.SelectedIndex = 0
                            }

                        }
                        catch
                        {
                            throw "Unable to load WIM metadata!"
                        }
                        finally
                        {
                            $tempOpenWim.Close()
                            Write-W2VTrace "Closing WIM metadata..."
                        }
                    }
                }

                $OnLoadForm_StateCorrection = {

                    # Correct the initial state of the form to prevent the .Net maximized form issue
                    $frmMain.WindowState      = $InitialFormWindowState
                }

                #endregion Event scriptblocks

                # Figure out VHD size and size unit.
                $unit = $null
                switch ([Math]::Round($SizeBytes.ToString().Length / 3))
                {
                    3 { $unit = "MB"; break }
                    4 { $unit = "GB"; break }
                    5 { $unit = "TB"; break }
                    default { $unit = ""; break }
                }

                $quantity = Invoke-Expression -Command "$($SizeBytes) / 1$($unit)"

                #region Form Code
                #region frmMain
                $frmMain.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 579
                $System_Drawing_Size.Width    = 512
                $frmMain.ClientSize           = $System_Drawing_Size
                $frmMain.Font                 = New-Object System.Drawing.Font("Segoe UI",10,0,3,1)
                $frmMain.FormBorderStyle      = 1
                $frmMain.MaximizeBox          = $False
                $frmMain.MinimizeBox          = $False
                $frmMain.Name                 = "frmMain"
                $frmMain.StartPosition        = 1
                $frmMain.Text                 = "Convert-WindowsImage UI"
                #endregion frmMain

                #region groupBox4
                $groupBox4.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 10
                $System_Drawing_Point.Y       = 498
                $groupBox4.Location           = $System_Drawing_Point
                $groupBox4.Name               = "groupBox4"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 69
                $System_Drawing_Size.Width    = 489
                $groupBox4.Size               = $System_Drawing_Size
                $groupBox4.TabIndex           = 8
                $groupBox4.TabStop            = $False
                $groupBox4.Text               = "4. Make the VHD!"

                $frmMain.Controls.Add($groupBox4)
                #endregion groupBox4

                #region btnGo
                $btnGo.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 39
                $System_Drawing_Point.Y       = 24
                $btnGo.Location               = $System_Drawing_Point
                $btnGo.Name                   = "btnGo"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 33
                $System_Drawing_Size.Width    = 415
                $btnGo.Size                   = $System_Drawing_Size
                $btnGo.TabIndex               = 0
                $btnGo.Text                   = "&Make my VHD"
                $btnGo.UseVisualStyleBackColor = $True
                $btnGo.DialogResult           = "OK"
                $btnGo.add_Click($btnGo_OnClick)

                $groupBox4.Controls.Add($btnGo)
                $frmMain.AcceptButton = $btnGo
                #endregion btnGo

                #region groupBox3
                $groupBox3.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 10
                $System_Drawing_Point.Y       = 243
                $groupBox3.Location           = $System_Drawing_Point
                $groupBox3.Name               = "groupBox3"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 245
                $System_Drawing_Size.Width    = 489
                $groupBox3.Size               = $System_Drawing_Size
                $groupBox3.TabIndex           = 7
                $groupBox3.TabStop            = $False
                $groupBox3.Text               = "3. Choose configuration options"

                $frmMain.Controls.Add($groupBox3)
                #endregion groupBox3

                #region txtVhdName
                $txtVhdName.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 25
                $System_Drawing_Point.Y       = 150
                $txtVhdName.Location          = $System_Drawing_Point
                $txtVhdName.Name              = "txtVhdName"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 418
                $txtVhdName.Size              = $System_Drawing_Size
                $txtVhdName.TabIndex          = 10

                $groupBox3.Controls.Add($txtVhdName)
                #endregion txtVhdName

                #region txtUnattendFile
                $txtUnattendFile.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 25
                $System_Drawing_Point.Y       = 198
                $txtUnattendFile.Location     = $System_Drawing_Point
                $txtUnattendFile.Name         = "txtUnattendFile"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 418
                $txtUnattendFile.Size         = $System_Drawing_Size
                $txtUnattendFile.TabIndex     = 11

                $groupBox3.Controls.Add($txtUnattendFile)
                #endregion txtUnattendFile

                #region label7
                $label7.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 23
                $System_Drawing_Point.Y       = 180
                $label7.Location              = $System_Drawing_Point
                $label7.Name                  = "label7"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 23
                $System_Drawing_Size.Width    = 175
                $label7.Size                  = $System_Drawing_Size
                $label7.Text                  = "Unattend File (Optional)"

                $groupBox3.Controls.Add($label7)
                #endregion label7

                #region label6
                $label6.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 23
                $System_Drawing_Point.Y       = 132
                $label6.Location              = $System_Drawing_Point
                $label6.Name                  = "label6"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 23
                $System_Drawing_Size.Width    = 175
                $label6.Size                  = $System_Drawing_Size
                $label6.Text                  = "VHD Name (Optional)"

                $groupBox3.Controls.Add($label6)
                #endregion label6

                #region btnUnattendBrowse
                $btnUnattendBrowse.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 449
                $System_Drawing_Point.Y       = 199
                $btnUnattendBrowse.Location   = $System_Drawing_Point
                $btnUnattendBrowse.Name       = "btnUnattendBrowse"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 27
                $btnUnattendBrowse.Size       = $System_Drawing_Size
                $btnUnattendBrowse.TabIndex   = 9
                $btnUnattendBrowse.Text       = "..."
                $btnUnattendBrowse.UseVisualStyleBackColor = $True
                $btnUnattendBrowse.add_Click($btnUnattendBrowse_OnClick)

                $groupBox3.Controls.Add($btnUnattendBrowse)
                #endregion btnUnattendBrowse

                #region btnWrkBrowse
                $btnWrkBrowse.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 449
                $System_Drawing_Point.Y       = 98
                $btnWrkBrowse.Location        = $System_Drawing_Point
                $btnWrkBrowse.Name            = "btnWrkBrowse"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 27
                $btnWrkBrowse.Size            = $System_Drawing_Size
                $btnWrkBrowse.TabIndex        = 9
                $btnWrkBrowse.Text            = "..."
                $btnWrkBrowse.UseVisualStyleBackColor = $True
                $btnWrkBrowse.add_Click($btnWrkBrowse_OnClick)

                $groupBox3.Controls.Add($btnWrkBrowse)
                #endregion btnWrkBrowse

                #region cmbVhdSizeUnit
                $cmbVhdSizeUnit.DataBindings.DefaultDataSourceUpdateMode = 0
                $cmbVhdSizeUnit.FormattingEnabled = $True
                $cmbVhdSizeUnit.Items.Add("MB") | Out-Null
                $cmbVhdSizeUnit.Items.Add("GB") | Out-Null
                $cmbVhdSizeUnit.Items.Add("TB") | Out-Null
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 409
                $System_Drawing_Point.Y       = 42
                $cmbVhdSizeUnit.Location      = $System_Drawing_Point
                $cmbVhdSizeUnit.Name          = "cmbVhdSizeUnit"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 67
                $cmbVhdSizeUnit.Size          = $System_Drawing_Size
                $cmbVhdSizeUnit.TabIndex      = 5
                $cmbVhdSizeUnit.Text          = $unit

                $groupBox3.Controls.Add($cmbVhdSizeUnit)
                #endregion cmbVhdSizeUnit

                #region numVhdSize
                $numVhdSize.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 340
                $System_Drawing_Point.Y       = 42
                $numVhdSize.Location          = $System_Drawing_Point
                $numVhdSize.Name              = "numVhdSize"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 63
                $numVhdSize.Size              = $System_Drawing_Size
                $numVhdSize.TabIndex          = 4
                $numVhdSize.Value             = $quantity

                $groupBox3.Controls.Add($numVhdSize)
                #endregion numVhdSize

                #region cmbVhdFormat
                $cmbVhdFormat.DataBindings.DefaultDataSourceUpdateMode = 0
                $cmbVhdFormat.FormattingEnabled = $True
                $cmbVhdFormat.Items.Add("VHD")  | Out-Null
                $cmbVhdFormat.Items.Add("VHDX") | Out-Null
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 25
                $System_Drawing_Point.Y       = 42
                $cmbVhdFormat.Location        = $System_Drawing_Point
                $cmbVhdFormat.Name            = "cmbVhdFormat"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 136
                $cmbVhdFormat.Size            = $System_Drawing_Size
                $cmbVhdFormat.TabIndex        = 0
                $cmbVhdFormat.Text            = $VHDFormat

                $groupBox3.Controls.Add($cmbVhdFormat)
                #endregion cmbVhdFormat

                #region label5
                $label5.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 23
                $System_Drawing_Point.Y       = 76
                $label5.Location              = $System_Drawing_Point
                $label5.Name                  = "label5"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 23
                $System_Drawing_Size.Width    = 264
                $label5.Size                  = $System_Drawing_Size
                $label5.TabIndex              = 8
                $label5.Text                  = "Working Directory"

                $groupBox3.Controls.Add($label5)
                #endregion label5

                #region txtWorkingDirectory
                $txtWorkingDirectory.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 25
                $System_Drawing_Point.Y       = 99
                $txtWorkingDirectory.Location = $System_Drawing_Point
                $txtWorkingDirectory.Name     = "txtWorkingDirectory"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 418
                $txtWorkingDirectory.Size     = $System_Drawing_Size
                $txtWorkingDirectory.TabIndex = 7
                $txtWorkingDirectory.Text     = $WorkingDirectory

                $groupBox3.Controls.Add($txtWorkingDirectory)
                #endregion txtWorkingDirectory

                #region label4
                $label4.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 340
                $System_Drawing_Point.Y       = 21
                $label4.Location              = $System_Drawing_Point
                $label4.Name                  = "label4"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 27
                $System_Drawing_Size.Width    = 86
                $label4.Size                  = $System_Drawing_Size
                $label4.TabIndex              = 6
                $label4.Text                  = "VHD Size"

                $groupBox3.Controls.Add($label4)
                #endregion label4

                #region label3
                $label3.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 176
                $System_Drawing_Point.Y       = 21
                $label3.Location              = $System_Drawing_Point
                $label3.Name                  = "label3"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 27
                $System_Drawing_Size.Width    = 92
                $label3.Size                  = $System_Drawing_Size
                $label3.TabIndex              = 3
                $label3.Text                  = "VHD Type"

                $groupBox3.Controls.Add($label3)
                #endregion label3

                #region label2
                $label2.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 25
                $System_Drawing_Point.Y       = 21
                $label2.Location              = $System_Drawing_Point
                $label2.Name                  = "label2"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 30
                $System_Drawing_Size.Width    = 118
                $label2.Size                  = $System_Drawing_Size
                $label2.TabIndex              = 1
                $label2.Text                  = "VHD Format"

                $groupBox3.Controls.Add($label2)
                #endregion label2

                #region groupBox2
                $groupBox2.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 10
                $System_Drawing_Point.Y       = 169
                $groupBox2.Location           = $System_Drawing_Point
                $groupBox2.Name               = "groupBox2"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 68
                $System_Drawing_Size.Width    = 490
                $groupBox2.Size               = $System_Drawing_Size
                $groupBox2.TabIndex           = 6
                $groupBox2.TabStop            = $False
                $groupBox2.Text               = "2. Choose a SKU from the list"

                $frmMain.Controls.Add($groupBox2)
                #endregion groupBox2

                #region cmbSkuList
                $cmbSkuList.DataBindings.DefaultDataSourceUpdateMode = 0
                $cmbSkuList.FormattingEnabled = $True
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 25
                $System_Drawing_Point.Y       = 24
                $cmbSkuList.Location          = $System_Drawing_Point
                $cmbSkuList.Name              = "cmbSkuList"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 452
                $cmbSkuList.Size              = $System_Drawing_Size
                $cmbSkuList.TabIndex          = 2

                $groupBox2.Controls.Add($cmbSkuList)
                #endregion cmbSkuList

                #region label1
                $label1.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 23
                $System_Drawing_Point.Y       = 21
                $label1.Location              = $System_Drawing_Point
                $label1.Name                  = "label1"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 71
                $System_Drawing_Size.Width    = 464
                $label1.Size                  = $System_Drawing_Size
                $label1.TabIndex              = 5
                $label1.Text                  = $uiHeader

                $frmMain.Controls.Add($label1)
                #endregion label1

                #region groupBox1
                $groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 10
                $System_Drawing_Point.Y       = 95
                $groupBox1.Location           = $System_Drawing_Point
                $groupBox1.Name               = "groupBox1"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 68
                $System_Drawing_Size.Width    = 490
                $groupBox1.Size               = $System_Drawing_Size
                $groupBox1.TabIndex           = 4
                $groupBox1.TabStop            = $False
                $groupBox1.Text               = "1. Choose a source"

                $frmMain.Controls.Add($groupBox1)
                #endregion groupBox1

                #region txtSourcePath
                $txtSourcePath.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 25
                $System_Drawing_Point.Y       = 24
                $txtSourcePath.Location       = $System_Drawing_Point
                $txtSourcePath.Name           = "txtSourcePath"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 418
                $txtSourcePath.Size           = $System_Drawing_Size
                $txtSourcePath.TabIndex       = 0

                $groupBox1.Controls.Add($txtSourcePath)
                #endregion txtSourcePath

                #region btnBrowseWim
                $btnBrowseWim.DataBindings.DefaultDataSourceUpdateMode = 0
                $System_Drawing_Point         = New-Object System.Drawing.Point
                $System_Drawing_Point.X       = 449
                $System_Drawing_Point.Y       = 24
                $btnBrowseWim.Location        = $System_Drawing_Point
                $btnBrowseWim.Name            = "btnBrowseWim"
                $System_Drawing_Size          = New-Object System.Drawing.Size
                $System_Drawing_Size.Height   = 25
                $System_Drawing_Size.Width    = 28
                $btnBrowseWim.Size            = $System_Drawing_Size
                $btnBrowseWim.TabIndex        = 1
                $btnBrowseWim.Text            = "..."
                $btnBrowseWim.UseVisualStyleBackColor = $True
                $btnBrowseWim.add_Click($btnBrowseWim_OnClick)

                $groupBox1.Controls.Add($btnBrowseWim)
                #endregion btnBrowseWim

                $openFileDialog1.FileName     = "openFileDialog1"
                $openFileDialog1.ShowHelp     = $True

                #endregion Form Code

                # Save the initial state of the form
                $InitialFormWindowState       = $frmMain.WindowState

                # Init the OnLoad event to correct the initial state of the form
                $frmMain.add_Load($OnLoadForm_StateCorrection)

                # Return the constructed form.
                $ret = $frmMain.ShowDialog()

                if (!($ret -ilike "OK"))
                {
                    throw "Form session has been cancelled."
                }

                if ([string]::IsNullOrEmpty($SourcePath))
                {
                    throw "No source path specified."
                }

                # VHD Format
                $VHDFormat        = $cmbVhdFormat.SelectedItem

                # VHD Size
                $SizeBytes        = Invoke-Expression "$($numVhdSize.Value)$($cmbVhdSizeUnit.SelectedItem)"

                # Working Directory
                $WorkingDirectory = $txtWorkingDirectory.Text

                # VHDPath
                if (![string]::IsNullOrEmpty($txtVhdName.Text))
                {
                    $VHDPath      = "$($WorkingDirectory)\$($txtVhdName.Text)"
                }

                # Edition
                if (![string]::IsNullOrEmpty($cmbSkuList.SelectedItem))
                {
                    $Edition      = $cmbSkuList.SelectedItem
                }

                # Because we used ShowDialog, we need to manually dispose of the form.
                # This probably won't make much of a difference, but let's free up all of the resources we can
                # before we start the conversion process.

                $frmMain.Dispose()
            }

            if ($VHDFormat -ilike "AUTO")
            {
                if ($DiskLayout -eq "BIOS")
                {
                    $VHDFormat = "VHD"
                }
                else
                {
                    $VHDFormat = "VHDX"
                }
            }

            #
            # Choose smallest supported block size for dynamic VHD(X)
            #
            $BlockSizeBytes = 1MB

            # There's a difference between the maximum sizes for VHDs and VHDXs. Make sure we follow it.
            if ("VHD" -ilike $VHDFormat)
            {
                if ($SizeBytes -gt $vhdMaxSize)
                {
                    Write-W2VWarn "For the VHD file format, the maximum file size is ~2040GB. We're automatically setting the size to 2040GB for you."
                    $SizeBytes = 2040GB
                }

                $BlockSizeBytes = 512KB
            }

            # Check if -VHDPath and -WorkingDirectory were both specified.
            if ((![String]::IsNullOrEmpty($VHDPath)) -and (![String]::IsNullOrEmpty($WorkingDirectory)))
            {
                if ($WorkingDirectory -ne $pwd)
                {
                    # If the WorkingDirectory is anything besides $pwd, tell people that the WorkingDirectory is being ignored.
                    Write-W2VWarn "Specifying -VHDPath and -WorkingDirectory at the same time is contradictory."
                    Write-W2VWarn "Ignoring the WorkingDirectory specification."
                    $WorkingDirectory = Split-Path $VHDPath -Parent
                }
            }

            if ($VHDPath)
            {
                # Check to see if there's a conflict between the specified file extension and the VHDFormat being used.
                $ext = ([IO.FileInfo]$VHDPath).Extension

                if (!($ext -ilike ".$($VHDFormat)"))
                {
                    throw "There is a mismatch between the VHDPath file extension ($($ext.ToUpper())), and the VHDFormat (.$($VHDFormat)). Please ensure that these match and try again."
                }
            }

            # Create a temporary name for the VHD(x). We'll name it properly at the end of the script.
            if ([String]::IsNullOrEmpty($VHDPath))
            {
                $VHDPath      = Join-Path $WorkingDirectory "$($sessionKey).$($VHDFormat.ToLower())"
            }
            else
            {
                # Since we can't do Resolve-Path against a file that doesn't exist, we need to get creative in determining
                # the full path that the user specified (or meant to specify if they gave us a relative path).
                # Check to see if the path has a root specified. If it doesn't, use the working directory.
                if (![IO.Path]::IsPathRooted($VHDPath))
                {
                    $VHDPath  = Join-Path $WorkingDirectory $VHDPath
                }

                $vhdFinalName = Split-Path $VHDPath -Leaf
                $VHDPath      = Join-Path (Split-Path $VHDPath -Parent) "$($sessionKey).$($VHDFormat.ToLower())"
            }

            Write-W2VTrace "Temporary $VHDFormat path is : $VHDPath"

            # If we're using an ISO, mount it and get the path to the WIM file.
            if (([IO.FileInfo]$SourcePath).Extension -ilike ".ISO")
            {
                # If the ISO isn't local, copy it down so we don't have to worry about resource contention
                # or about network latency.
                if (Test-IsNetworkLocation $SourcePath)
                {
                    Write-W2VInfo "Copying ISO $(Split-Path $SourcePath -Leaf) to temp folder..."
                    robocopy $(Split-Path $SourcePath -Parent) $TempDirectory $(Split-Path $SourcePath -Leaf) | Out-Null
                    $SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)"

                    $tempSource = $SourcePath
                }

                $isoPath = (Resolve-Path $SourcePath).Path

                Write-W2VInfo "Opening ISO $(Split-Path $isoPath -Leaf)..."
                $openIso     = Mount-DiskImage -ImagePath $isoPath -StorageType ISO -PassThru
                # Refresh the DiskImage object so we can get the real information about it. I assume this is a bug.
                $openIso     = Get-DiskImage -ImagePath $isoPath
                $driveLetter = ($openIso | Get-Volume).DriveLetter

                $SourcePath  = "$($driveLetter):\sources\install.wim"

                # Check to see if there's a WIM file we can muck about with.
                Write-W2VInfo "Looking for $($SourcePath)..."
                if (!(Test-Path $SourcePath))
                {
                    throw "The specified ISO does not appear to be valid Windows installation media."
                }
            }

            # Check to see if the WIM is local, or on a network location. If the latter, copy it locally.
            if (Test-IsNetworkLocation $SourcePath)
            {
                Write-W2VInfo "Copying WIM $(Split-Path $SourcePath -Leaf) to temp folder..."
                robocopy $(Split-Path $SourcePath -Parent) $TempDirectory $(Split-Path $SourcePath -Leaf) | Out-Null
                $SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)"

                $tempSource = $SourcePath
            }

            $SourcePath  = (Resolve-Path $SourcePath).Path

            ####################################################################################################
            # QUERY WIM INFORMATION AND EXTRACT THE INDEX OF TARGETED IMAGE
            ####################################################################################################

            Write-W2VInfo "Looking for the requested Windows image in the WIM file"
            $WindowsImage = Get-WindowsImage -ImagePath $SourcePath

            if (-not $WindowsImage -or ($WindowsImage -is [System.Array]))
            {
                #
                # WIM may have multiple images. Filter on Edition (can be index or name) and try to find a unique image
                #
                $EditionIndex = 0;
                if ([Int32]::TryParse($Edition, [ref]$EditionIndex))
                {
                    $WindowsImage = Get-WindowsImage -ImagePath $SourcePath -Index $EditionIndex
                }
                else
                {
                    $WindowsImage = Get-WindowsImage -ImagePath $SourcePath | Where-Object {$_.ImageName -ilike "*$($Edition)"}
                }

                if (-not $WindowsImage)
                {
                    throw "Requested windows Image was not found on the WIM file!"
                }
                if ($WindowsImage -is [System.Array])
                {
                    Write-W2VInfo "WIM file has the following $($WindowsImage.Count) images that match filter *$($Edition)"
                    Get-WindowsImage -ImagePath $SourcePath

                    Write-W2VError "You must specify an Edition or SKU index, since the WIM has more than one image."
                    throw "There are more than one images that match ImageName filter *$($Edition)"
                }
            }

            $ImageIndex = $WindowsImage[0].ImageIndex

            # We're good. Open the WIM container.
            # NOTE: this is only required because we want to get the XML-based meta-data at the end. Is there a better way?
            # If we can get this information from DISM cmdlets, we can remove the openWim constructs
            $openWim     = New-Object WIM2VHD.WimFile $SourcePath

            $openImage = $openWim[[Int32]$ImageIndex]

            if ($null -eq $openImage)
            {
                Write-W2VError "The specified edition does not appear to exist in the specified WIM."
                Write-W2VError "Valid edition names are:"
                $openWim.Images | %{ Write-W2VError " $($_.ImageFlags)" }
                throw
            }

            Write-W2VInfo "Image $($openImage.ImageIndex) selected ($($openImage.ImageFlags))..."

            # Check to make sure that the image we're applying is Windows 7 or greater.
            if ($openImage.ImageVersion -lt $lowestSupportedVersion)
            {
                if ($openImage.ImageVersion -eq "0.0.0.0")
                {
                    Write-W2VWarn "The specified WIM does not encode the Windows version."
                }
                else
                {
                    throw "Convert-WindowsImage only supports Windows 7 and Windows 8 WIM files. The specified image (version $($openImage.ImageVersion)) does not appear to contain one of those operating systems."
                }
            }

            if ($hyperVEnabled)
            {
                Write-W2VInfo "Creating sparse disk..."
                $newVhd = New-VHD -Path $VHDPath -SizeBytes $SizeBytes -BlockSizeBytes $BlockSizeBytes -Dynamic

                Write-W2VInfo "Mounting $VHDFormat..."
                $disk = $newVhd | Mount-VHD -PassThru | Get-Disk
            }
            else
            {
                <#
                    Create the VHD using the VirtDisk Win32 API.
                    So, why not use the New-VHD cmdlet here?
 
                    New-VHD depends on the Hyper-V Cmdlets, which aren't installed by default.
                    Installing those cmdlets isn't a big deal, but they depend on the Hyper-V WMI
                    APIs, which in turn depend on Hyper-V. In order to prevent Convert-WindowsImage
                    from being dependent on Hyper-V (and thus, x64 systems only), we're using the
                    VirtDisk APIs directly.
                #>


                Write-W2VInfo "Creating sparse disk..."
                [WIM2VHD.VirtualHardDisk]::CreateSparseDisk(
                    $VHDFormat,
                    $VHDPath,
                    $SizeBytes,
                    $true
                )

                # Attach the VHD.\
                Write-W2VInfo "Attaching $VHDFormat..."
                $disk = Mount-DiskImage -ImagePath $VHDPath -PassThru | Get-DiskImage | Get-Disk
            }

            switch ($DiskLayout)
            {
                "BIOS"
                {
                    Write-W2VInfo "Initializing disk..."
                    Initialize-Disk -Number $disk.Number -PartitionStyle MBR

                    #
                    # Create the Windows/system partition
                    #
                    Write-W2VInfo "Creating single partition..."
                    $systemPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -MbrType IFS -IsActive
                    $windowsPartition = $systemPartition

                    Write-W2VInfo "Formatting windows volume..."
                    $systemVolume = Format-Volume -Partition $systemPartition -FileSystem NTFS -Force -Confirm:$false
                    $windowsVolume = $systemVolume
                }

                "UEFI"
                {
                    Write-W2VInfo "Initializing disk..."
                    Initialize-Disk -Number $disk.Number -PartitionStyle GPT

                    if ((Get-WindowsBuildNumber) -ge 10240)
                    {
                        #
                        # Create the system partition. Create a data partition so we can format it, then change to ESP
                        #
                        Write-W2VInfo "Creating EFI system partition..."
                        $systemPartition = New-Partition -DiskNumber $disk.Number -Size 200MB -GptType '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}'

                        Write-W2VInfo "Formatting system volume..."
                        $systemVolume = Format-Volume -Partition $systemPartition -FileSystem FAT32 -Force -Confirm:$false

                        Write-W2VInfo "Setting system partition as ESP..."
                        $systemPartition | Set-Partition -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}'
                        $systemPartition | Add-PartitionAccessPath -AssignDriveLetter
                    }
                    else
                    {
                        #
                        # Create the system partition
                        #
                        Write-W2VInfo "Creating EFI system partition (ESP)..."
                        $systemPartition = New-Partition -DiskNumber $disk.Number -Size 200MB -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' -AssignDriveLetter

                        Write-W2VInfo "Formatting ESP..."
                        $formatArgs = @(
                            "$($systemPartition.DriveLetter):", # Partition drive letter
                            "/FS:FAT32",                        # File system
                            "/Q",                               # Quick format
                            "/Y"                                # Suppress prompt
                            )

                        Run-Executable -Executable format -Arguments $formatArgs
                    }

                    #
                    # Create the reserved partition
                    #
                    Write-W2VInfo "Creating MSR partition..."
                    $reservedPartition = New-Partition -DiskNumber $disk.Number -Size 128MB -GptType '{e3c9e316-0b5c-4db8-817d-f92df00215ae}'

                    #
                    # Create the Windows partition
                    #
                    Write-W2VInfo "Creating windows partition..."
                    $windowsPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -GptType '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}'

                    Write-W2VInfo "Formatting windows volume..."
                    $windowsVolume = Format-Volume -Partition $windowsPartition -FileSystem NTFS -Force -Confirm:$false
                }

                "WindowsToGo"
                {
                    Write-W2VInfo "Initializing disk..."
                    Initialize-Disk -Number $disk.Number -PartitionStyle MBR

                    #
                    # Create the system partition
                    #
                    Write-W2VInfo "Creating system partition..."
                    $systemPartition = New-Partition -DiskNumber $disk.Number -Size 350MB -MbrType FAT32 -IsActive

                    Write-W2VInfo "Formatting system volume..."
                    $systemVolume    = Format-Volume -Partition $systemPartition -FileSystem FAT32 -Force -Confirm:$false

                    #
                    # Create the Windows partition
                    #
                    Write-W2VInfo "Creating windows partition..."
                    $windowsPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -MbrType IFS

                    Write-W2VInfo "Formatting windows volume..."
                    $windowsVolume    = Format-Volume -Partition $windowsPartition -FileSystem NTFS -Force -Confirm:$false
                }
            }

            #
            # Assign drive letter to Windows partition. This is required for bcdboot
            #

            $attempts = 1
            $assigned = $false

            do
            {
                $windowsPartition | Add-PartitionAccessPath -AssignDriveLetter
                $windowsPartition = $windowsPartition | Get-Partition
                if($windowsPartition.DriveLetter -ne 0)
                {
                    $assigned = $true
                }
                else
                {
                    #sleep for up to 10 seconds and retry
                    Get-Random -Minimum 1 -Maximum 10 | Start-Sleep

                    $attempts++
                }
            }
            while ($attempts -le 100 -and -not($assigned))

            if (-not($assigned))
            {
                throw "Unable to get Partition after retry"
            }

            $windowsDrive = $(Get-Partition -Volume $windowsVolume).AccessPaths[0].substring(0,2)
            Write-W2VInfo "Windows path ($windowsDrive) has been assigned."
            Write-W2VInfo "Windows path ($windowsDrive) took $attempts attempts to be assigned."

            #
            # Refresh access paths (we have now formatted the volume)
            #
            $systemPartition = $systemPartition | Get-Partition
            $systemDrive = $systemPartition.AccessPaths[0].trimend("\").replace("\?", "??")
            Write-W2VInfo "System volume location: $systemDrive"

            ####################################################################################################
            # APPLY IMAGE FROM WIM TO THE NEW VHD
            ####################################################################################################

            Write-W2VInfo "Applying image to $VHDFormat. This could take a while..."
            if ((Get-Command Expand-WindowsImage -ErrorAction SilentlyContinue) -and ((-not $ApplyEA) -and ([string]::IsNullOrEmpty($DismPath))))
            {
                Expand-WindowsImage -ApplyPath $windowsDrive -ImagePath $SourcePath -Index $ImageIndex -LogPath "$($logFolder)\DismLogs.log" | Out-Null
            }
            else
            {
                if (![string]::IsNullOrEmpty($DismPath))
                {
                    $dismPath = $DismPath
                }
                else
                {
                    $dismPath = $(Join-Path (get-item env:\windir).value "system32\dism.exe")
                }

                $applyImage = "/Apply-Image"
                if ($ApplyEA)
                {
                    $applyImage = $applyImage + " /EA"
                }

                $dismArgs = @("$applyImage /ImageFile:`"$SourcePath`" /Index:$ImageIndex /ApplyDir:$windowsDrive /LogPath:`"$($logFolder)\DismLogs.log`"")
                Write-W2VInfo "Applying image: $dismPath $dismArgs"
                $process  = Start-Process -Passthru -Wait -NoNewWindow -FilePath $dismPath `
                            -ArgumentList $dismArgs `

                if ($process.ExitCode -ne 0)
                {
                     throw "Image Apply failed! See DismImageApply logs for details"
                }
            }
            Write-W2VInfo "Image was applied successfully. "

            #
            # Here we copy in the unattend file (if specified by the command line)
            #
            if (![string]::IsNullOrEmpty($UnattendPath))
            {
                Write-W2VInfo "Applying unattend file ($(Split-Path $UnattendPath -Leaf))..."
                Copy-Item -Path $UnattendPath -Destination (Join-Path $windowsDrive "unattend.xml") -Force
            }

            if (![string]::IsNullOrEmpty($MergeFolderPath))
            {
                Write-W2VInfo "Applying merge folder ($MergeFolderPath)..."
                Copy-Item -Recurse -Path (Join-Path $MergeFolderPath "*") -Destination $windowsDrive -Force #added to handle merge folders
            }

            if (($openImage.ImageArchitecture -ne "ARM") -and       # No virtualization platform for ARM images
                ($openImage.ImageArchitecture -ne "ARM64") -and     # No virtualization platform for ARM64 images
                ($BCDinVHD -ne "NativeBoot"))                       # User asked for a non-bootable image
            {
                if (Test-Path "$($systemDrive)\boot\bcd")
                {
                    Write-W2VInfo "Image already has BIOS BCD store..."
                }
                elseif (Test-Path "$($systemDrive)\efi\microsoft\boot\bcd")
                {
                    Write-W2VInfo "Image already has EFI BCD store..."
                }
                else
                {
                    Write-W2VInfo "Making image bootable..."
                    $bcdBootArgs = @(
                        "$($windowsDrive)\Windows", # Path to the \Windows on the VHD
                        "/s $systemDrive",          # Specifies the volume letter of the drive to create the \BOOT folder on.
                        "/v"                        # Enabled verbose logging.
                        )

                    switch ($DiskLayout)
                    {
                        "BIOS"
                        {
                            $bcdBootArgs += "/f BIOS"   # Specifies the firmware type of the target system partition
                        }

                        "UEFI"
                        {
                            $bcdBootArgs += "/f UEFI"   # Specifies the firmware type of the target system partition
                        }

                        "WindowsToGo"
                        {
                            # Create entries for both UEFI and BIOS if possible
                            if (Test-Path "$($windowsDrive)\Windows\boot\EFI\bootmgfw.efi")
                            {
                                $bcdBootArgs += "/f ALL"
                            }
                        }
                    }

                    Run-Executable -Executable $BCDBoot -Arguments $bcdBootArgs

                    # The following is added to mitigate the VMM diff disk handling
                    # We're going to change from MBRBootOption to LocateBootOption.

                    if ($DiskLayout -eq "BIOS")
                    {
                        Write-W2VInfo "Fixing the Device ID in the BCD store on $($VHDFormat)..."
                        Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
                            "/store $($systemDrive)\boot\bcd",
                            "/set `{bootmgr`} device locate"
                        )
                        Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
                            "/store $($systemDrive)\boot\bcd",
                            "/set `{default`} device locate"
                        )
                        Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
                            "/store $($systemDrive)\boot\bcd",
                            "/set `{default`} osdevice locate"
                        )
                    }
                }

                Write-W2VInfo "Drive is bootable. Cleaning up..."

                # Are we turning the debugger on?
                if ($EnableDebugger -inotlike "None")
                {
                    $bcdEditArgs = $null;

                    # Configure the specified debugging transport and other settings.
                    switch ($EnableDebugger)
                    {
                        "Serial"
                        {
                            $bcdEditArgs = @(
                                "/dbgsettings SERIAL",
                                "DEBUGPORT:$($ComPort.Value)",
                                "BAUDRATE:$($BaudRate.Value)"
                                )
                        }

                        "1394"
                        {
                            $bcdEditArgs = @(
                                "/dbgsettings 1394",
                                "CHANNEL:$($Channel.Value)"
                                )
                        }

                        "USB"
                        {
                            $bcdEditArgs = @(
                                "/dbgsettings USB",
                                "TARGETNAME:$($Target.Value)"
                                )
                        }

                        "Local"
                        {
                            $bcdEditArgs = @(
                                "/dbgsettings LOCAL"
                                )
                        }

                        "Network"
                        {
                            $bcdEditArgs = @(
                                "/dbgsettings NET",
                                "HOSTIP:$($IP.Value)",
                                "PORT:$($Port.Value)",
                                "KEY:$($Key.Value)"
                                )
                        }
                    }

                    $bcdStores = @(
                        "$($systemDrive)\boot\bcd",
                        "$($systemDrive)\efi\microsoft\boot\bcd"
                        )

                    foreach ($bcdStore in $bcdStores)
                    {
                        if (Test-Path $bcdStore)
                        {
                            Write-W2VInfo "Turning kernel debugging on in the $($VHDFormat) for $($bcdStore)..."
                            Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
                                "/store $($bcdStore)",
                                "/set `{default`} debug on"
                                )

                            $bcdEditArguments = @("/store $($bcdStore)") + $bcdEditArgs

                            Run-Executable -Executable "BCDEDIT.EXE" -Arguments $bcdEditArguments
                        }
                    }
                }
            }
            else
            {
                # Don't bother to check on debugging. We can't boot WoA VHDs in VMs, and
                # if we're native booting, the changes need to be made to the BCD store on the
                # physical computer's boot volume.

                Write-W2VInfo "Image applied. It is not bootable."
            }

            if ($RemoteDesktopEnable -or (-not $ExpandOnNativeBoot))
            {
                $hive = Mount-RegistryHive -Hive (Join-Path $windowsDrive "Windows\System32\Config\System")

                if ($RemoteDesktopEnable)
                {
                    Write-W2VInfo -text "Enabling Remote Desktop"
                    Set-ItemProperty -Path "HKLM:\$($hive)\ControlSet001\Control\Terminal Server" -Name "fDenyTSConnections" -Value 0
                }

                if (-not $ExpandOnNativeBoot)
                {
                    Write-W2VInfo -text "Disabling automatic $VHDFormat expansion for Native Boot"
                    Set-ItemProperty -Path "HKLM:\$($hive)\ControlSet001\Services\FsDepends\Parameters" -Name "VirtualDiskExpandOnMount" -Value 4
                }

                Dismount-RegistryHive -HiveMountPoint $hive
            }

            if ($Driver)
            {
                Write-W2VInfo -text "Adding Windows Drivers to the Image"
                $Driver | ForEach-Object -Process {
                    Write-W2VInfo -text "Driver path: $PSItem"
                    Add-WindowsDriver -Path $windowsDrive -Recurse -Driver $PSItem -Verbose | Out-Null
                }
            }

            If ($Feature)
            {
                Write-W2VInfo -text "Installing Windows Feature(s) $Feature to the Image"
                $FeatureSourcePath = Join-Path -Path "$($driveLetter):" -ChildPath "sources\sxs"
                Write-W2VInfo -text "From $FeatureSourcePath"
                Enable-WindowsOptionalFeature -FeatureName $Feature -Source $FeatureSourcePath -Path $windowsDrive -All | Out-Null
            }

            if ($Package)
            {
                Write-W2VInfo -text "Adding Windows Packages to the Image"

                $Package | ForEach-Object -Process {
                    Write-W2VInfo -text "Package path: $PSItem"
                    Add-WindowsPackage -Path $windowsDrive -PackagePath $PSItem | Out-Null
                }
            }

            #
            # Remove system partition access path, if necessary
            #
            if ($DiskLayout -eq "UEFI")
            {
                $systemPartition | Remove-PartitionAccessPath -AccessPath $systemPartition.AccessPaths[0]
            }

            if ([String]::IsNullOrEmpty($vhdFinalName))
            {
                # We need to generate a file name.
                Write-W2VInfo "Generating name for $($VHDFormat)..."
                $hive         = Mount-RegistryHive -Hive (Join-Path $windowsDrive "Windows\System32\Config\Software")

                $buildLabEx   = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").BuildLabEx
                $installType  = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").InstallationType
                $editionId    = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").EditionID
                $skuFamily    = $null

                Dismount-RegistryHive -HiveMountPoint $hive

                # Is this ServerCore?
                # Since we're only doing this string comparison against the InstallType key, we won't get
                # false positives with the Core SKU.
                if ($installType.ToUpper().Contains("CORE"))
                {
                    $editionId += "Core"
                }

                # What type of SKU are we?
                if ($installType.ToUpper().Contains("SERVER"))
                {
                    $skuFamily = "Server"
                }
                elseif ($installType.ToUpper().Contains("CLIENT"))
                {
                    $skuFamily = "Client"
                }
                else
                {
                    $skuFamily = "Unknown"
                }

                #
                # ISSUE - do we want VL here?
                #
                $vhdFinalName = "$($buildLabEx)_$($skuFamily)_$($editionId)_$($openImage.ImageDefaultLanguage).$($VHDFormat.ToLower())"
                Write-W2VTrace "$VHDFormat final name is : $vhdFinalName"
            }

            if ($hyperVEnabled)
            {
                Write-W2VInfo "Dismounting $VHDFormat..."
                Dismount-VHD -Path $VHDPath
            }
            else
            {
                Write-W2VInfo "Closing $VHDFormat..."
                Dismount-DiskImage -ImagePath $VHDPath
            }

            $vhdFinalPath = Join-Path (Split-Path $VHDPath -Parent) $vhdFinalName
            Write-W2VTrace "$VHDFormat final path is : $vhdFinalPath"

            if (Test-Path $vhdFinalPath)
            {
                Write-W2VInfo "Deleting pre-existing $VHDFormat : $(Split-Path $vhdFinalPath -Leaf)..."
                Remove-Item -Path $vhdFinalPath -Force
            }

            Write-W2VTrace -Text "Renaming $VHDFormat at $VHDPath to $vhdFinalName"
            Rename-Item -Path (Resolve-Path $VHDPath).Path -NewName $vhdFinalName -Force
            $vhd += Get-DiskImage -ImagePath $vhdFinalPath

            $vhdFinalName = $null
        }
        catch
        {
            Write-W2VError $_
            Write-W2VInfo "Log folder is $logFolder"
        }
        finally
        {
            # If we still have a WIM image open, close it.
            if ($openWim -ne $null)
            {
                Write-W2VInfo "Closing Windows image..."
                $openWim.Close()
            }

            # If we still have a registry hive mounted, dismount it.
            if ($mountedHive -ne $null)
            {
                Write-W2VInfo "Closing registry hive..."
                Dismount-RegistryHive -HiveMountPoint $mountedHive
            }

            # If VHD is mounted, unmount it
            if (Test-Path $VHDPath)
            {
                if ($hyperVEnabled)
                {
                    if ((Get-VHD -Path $VHDPath).Attached)
                    {
                        Dismount-VHD -Path $VHDPath
                    }
                }
                else
                {
                    Dismount-DiskImage -ImagePath $VHDPath
                }
            }

            # If we still have an ISO open, close it.
            if ($openIso -ne $null)
            {
                Write-W2VInfo "Closing ISO..."
                Dismount-DiskImage $ISOPath
            }

            if (-not $CacheSource)
            {
                if ($tempSource -and (Test-Path $tempSource))
                {
                    Remove-Item -Path $tempSource -Force
                }
            }

            # Close out the transcript and tell the user we're done.
            Write-W2VInfo "Done."
            if ($transcripting)
            {
                $null = Stop-Transcript
            }
        }
    }

    End
    {
        if ($Passthru)
        {
            return $vhd
        }
    }
    #endregion Code

}


function
Add-WindowsImageTypes
{
        $code      = @"
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.Win32.SafeHandles;
 
namespace WIM2VHD
{
 
/// <summary>
/// P/Invoke methods and associated enums, flags, and structs.
/// </summary>
public class
NativeMethods
{
 
    #region Delegates and Callbacks
    #region WIMGAPI
 
    ///<summary>
    ///User-defined function used with the RegisterMessageCallback or UnregisterMessageCallback function.
    ///</summary>
    ///<param name="MessageId">Specifies the message being sent.</param>
    ///<param name="wParam">Specifies additional message information. The contents of this parameter depend on the value of the
    ///MessageId parameter.</param>
    ///<param name="lParam">Specifies additional message information. The contents of this parameter depend on the value of the
    ///MessageId parameter.</param>
    ///<param name="UserData">Specifies the user-defined value passed to RegisterCallback.</param>
    ///<returns>
    ///To indicate success and to enable other subscribers to process the message return WIM_MSG_SUCCESS.
    ///To prevent other subscribers from receiving the message, return WIM_MSG_DONE.
    ///To cancel an image apply or capture, return WIM_MSG_ABORT_IMAGE when handling the WIM_MSG_PROCESS message.
    ///</returns>
    public delegate uint
    WimMessageCallback(
        uint MessageId,
        IntPtr wParam,
        IntPtr lParam,
        IntPtr UserData
    );
 
    public static void
    RegisterMessageCallback(
        WimFileHandle hWim,
        WimMessageCallback callback)
        {
 
        uint _callback = NativeMethods.WimRegisterMessageCallback(hWim, callback, IntPtr.Zero);
        int rc = Marshal.GetLastWin32Error();
        if (0 != rc)
        {
            // Throw an exception if something bad happened on the Win32 end.
            throw
                new InvalidOperationException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        "Unable to register message callback."
            ));
        }
    }
 
    public static void
    UnregisterMessageCallback(
        WimFileHandle hWim,
        WimMessageCallback registeredCallback)
        {
 
        bool status = NativeMethods.WimUnregisterMessageCallback(hWim, registeredCallback);
        int rc = Marshal.GetLastWin32Error();
        if (!status)
        {
            throw
                new InvalidOperationException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        "Unable to unregister message callback."
            ));
        }
    }
 
    #endregion WIMGAPI
    #endregion Delegates and Callbacks
 
    #region Constants
 
    #region VDiskInterop
 
    /// <summary>
    /// The default depth in a VHD parent chain that this library will search through.
    /// If you want to go more than one disk deep into the parent chain, provide a different value.
    /// </summary>
    public const uint OPEN_VIRTUAL_DISK_RW_DEFAULT_DEPTH = 0x00000001;
 
    public const uint DEFAULT_BLOCK_SIZE = 0x00080000;
    public const uint DISK_SECTOR_SIZE = 0x00000200;
 
    internal const uint ERROR_VIRTDISK_NOT_VIRTUAL_DISK = 0xC03A0015;
    internal const uint ERROR_NOT_FOUND = 0x00000490;
    internal const uint ERROR_IO_PENDING = 0x000003E5;
    internal const uint ERROR_INSUFFICIENT_BUFFER = 0x0000007A;
    internal const uint ERROR_ERROR_DEV_NOT_EXIST = 0x00000037;
    internal const uint ERROR_BAD_COMMAND = 0x00000016;
    internal const uint ERROR_SUCCESS = 0x00000000;
 
    public const uint GENERIC_READ = 0x80000000;
    public const uint GENERIC_WRITE = 0x40000000;
    public const short FILE_ATTRIBUTE_NORMAL = 0x00000080;
    public const uint CREATE_NEW = 0x00000001;
    public const uint CREATE_ALWAYS = 0x00000002;
    public const uint OPEN_EXISTING = 0x00000003;
    public const short INVALID_HANDLE_VALUE = -1;
 
    internal static Guid VirtualStorageTypeVendorUnknown = new Guid("00000000-0000-0000-0000-000000000000");
    internal static Guid VirtualStorageTypeVendorMicrosoft = new Guid("EC984AEC-A0F9-47e9-901F-71415A66345B");
 
    #endregion VDiskInterop
 
    #region WIMGAPI
 
    public const uint WIM_FLAG_VERIFY = 0x00000002;
    public const uint WIM_FLAG_INDEX = 0x00000004;
 
    public const uint WM_APP = 0x00008000;
 
    #endregion WIMGAPI
 
    #endregion Constants
 
    #region Enums and Flags
 
    #region VDiskInterop
 
    /// <summary>
    /// Indicates the version of the virtual disk to create.
    /// </summary>
    public enum CreateVirtualDiskVersion : int
    {
        VersionUnspecified = 0x00000000,
        Version1 = 0x00000001,
        Version2 = 0x00000002
    }
 
    public enum OpenVirtualDiskVersion : int
    {
        VersionUnspecified = 0x00000000,
        Version1 = 0x00000001,
        Version2 = 0x00000002
    }
 
    /// <summary>
    /// Contains the version of the virtual hard disk (VHD) ATTACH_VIRTUAL_DISK_PARAMETERS structure to use in calls to VHD functions.
    /// </summary>
    public enum AttachVirtualDiskVersion : int
    {
        VersionUnspecified = 0x00000000,
        Version1 = 0x00000001,
        Version2 = 0x00000002
    }
 
    public enum CompactVirtualDiskVersion : int
    {
        VersionUnspecified = 0x00000000,
        Version1 = 0x00000001
    }
 
    /// <summary>
    /// Contains the type and provider (vendor) of the virtual storage device.
    /// </summary>
    public enum VirtualStorageDeviceType : int
    {
        /// <summary>
        /// The storage type is unknown or not valid.
        /// </summary>
        Unknown = 0x00000000,
        /// <summary>
        /// For internal use only. This type is not supported.
        /// </summary>
        ISO = 0x00000001,
        /// <summary>
        /// Virtual Hard Disk device type.
        /// </summary>
        VHD = 0x00000002,
        /// <summary>
        /// Virtual Hard Disk v2 device type.
        /// </summary>
        VHDX = 0x00000003
    }
 
    /// <summary>
    /// Contains virtual hard disk (VHD) open request flags.
    /// </summary>
    [Flags]
    public enum OpenVirtualDiskFlags
    {
        /// <summary>
        /// No flags. Use system defaults.
        /// </summary>
        None = 0x00000000,
        /// <summary>
        /// Open the VHD file (backing store) without opening any differencing-chain parents. Used to correct broken parent links.
        /// </summary>
        NoParents = 0x00000001,
        /// <summary>
        /// Reserved.
        /// </summary>
        BlankFile = 0x00000002,
        /// <summary>
        /// Reserved.
        /// </summary>
        BootDrive = 0x00000004,
    }
 
    /// <summary>
    /// Contains the bit mask for specifying access rights to a virtual hard disk (VHD).
    /// </summary>
    [Flags]
    public enum VirtualDiskAccessMask
    {
        /// <summary>
        /// Only Version2 of OpenVirtualDisk API accepts this parameter
        /// </summary>
        None = 0x00000000,
        /// <summary>
        /// Open the virtual disk for read-only attach access. The caller must have READ access to the virtual disk image file.
        /// </summary>
        /// <remarks>
        /// If used in a request to open a virtual disk that is already open, the other handles must be limited to either
        /// VIRTUAL_DISK_ACCESS_DETACH or VIRTUAL_DISK_ACCESS_GET_INFO access, otherwise the open request with this flag will fail.
        /// </remarks>
        AttachReadOnly = 0x00010000,
        /// <summary>
        /// Open the virtual disk for read-write attaching access. The caller must have (READ | WRITE) access to the virtual disk image file.
        /// </summary>
        /// <remarks>
        /// If used in a request to open a virtual disk that is already open, the other handles must be limited to either
        /// VIRTUAL_DISK_ACCESS_DETACH or VIRTUAL_DISK_ACCESS_GET_INFO access, otherwise the open request with this flag will fail.
        /// If the virtual disk is part of a differencing chain, the disk for this request cannot be less than the readWriteDepth specified
        /// during the prior open request for that differencing chain.
        /// </remarks>
        AttachReadWrite = 0x00020000,
        /// <summary>
        /// Open the virtual disk to allow detaching of an attached virtual disk. The caller must have
        /// (FILE_READ_ATTRIBUTES | FILE_READ_DATA) access to the virtual disk image file.
        /// </summary>
        Detach = 0x00040000,
        /// <summary>
        /// Information retrieval access to the virtual disk. The caller must have READ access to the virtual disk image file.
        /// </summary>
        GetInfo = 0x00080000,
        /// <summary>
        /// Virtual disk creation access.
        /// </summary>
        Create = 0x00100000,
        /// <summary>
        /// Open the virtual disk to perform offline meta-operations. The caller must have (READ | WRITE) access to the virtual
        /// disk image file, up to readWriteDepth if working with a differencing chain.
        /// </summary>
        /// <remarks>
        /// If the virtual disk is part of a differencing chain, the backing store (host volume) is opened in RW exclusive mode up to readWriteDepth.
        /// </remarks>
        MetaOperations = 0x00200000,
        /// <summary>
        /// Reserved.
        /// </summary>
        Read = 0x000D0000,
        /// <summary>
        /// Allows unrestricted access to the virtual disk. The caller must have unrestricted access rights to the virtual disk image file.
        /// </summary>
        All = 0x003F0000,
        /// <summary>
        /// Reserved.
        /// </summary>
        Writable = 0x00320000
    }
 
    /// <summary>
    /// Contains virtual hard disk (VHD) creation flags.
    /// </summary>
    [Flags]
    public enum CreateVirtualDiskFlags
    {
        /// <summary>
        /// Contains virtual hard disk (VHD) creation flags.
        /// </summary>
        None = 0x00000000,
        /// <summary>
        /// Pre-allocate all physical space necessary for the size of the virtual disk.
        /// </summary>
        /// <remarks>
        /// The CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION flag is used for the creation of a fixed VHD.
        /// </remarks>
        FullPhysicalAllocation = 0x00000001
    }
 
    /// <summary>
    /// Contains virtual disk attach request flags.
    /// </summary>
    [Flags]
    public enum AttachVirtualDiskFlags
    {
        /// <summary>
        /// No flags. Use system defaults.
        /// </summary>
        None = 0x00000000,
        /// <summary>
        /// Attach the virtual disk as read-only.
        /// </summary>
        ReadOnly = 0x00000001,
        /// <summary>
        /// No drive letters are assigned to the disk's volumes.
        /// </summary>
        /// <remarks>Oddly enough, this doesn't apply to NTFS mount points.</remarks>
        NoDriveLetter = 0x00000002,
        /// <summary>
        /// Will decouple the virtual disk lifetime from that of the VirtualDiskHandle.
        /// The virtual disk will be attached until the Detach() function is called, even if all open handles to the virtual disk are closed.
        /// </summary>
        PermanentLifetime = 0x00000004,
        /// <summary>
        /// Reserved.
        /// </summary>
        NoLocalHost = 0x00000008
    }
 
    [Flags]
    public enum DetachVirtualDiskFlag
    {
        None = 0x00000000
    }
 
    [Flags]
    public enum CompactVirtualDiskFlags
    {
        None = 0x00000000,
        NoZeroScan = 0x00000001,
        NoBlockMoves = 0x00000002
    }
 
    #endregion VDiskInterop
 
    #region WIMGAPI
 
    [FlagsAttribute]
    internal enum
    WimCreateFileDesiredAccess : uint
        {
        WimQuery = 0x00000000,
        WimGenericRead = 0x80000000
    }
 
    public enum WimMessage : uint
    {
        WIM_MSG = WM_APP + 0x1476,
        WIM_MSG_TEXT,
        ///<summary>
        ///Indicates an update in the progress of an image application.
        ///</summary>
        WIM_MSG_PROGRESS,
        ///<summary>
        ///Enables the caller to prevent a file or a directory from being captured or applied.
        ///</summary>
        WIM_MSG_PROCESS,
        ///<summary>
        ///Indicates that volume information is being gathered during an image capture.
        ///</summary>
        WIM_MSG_SCANNING,
        ///<summary>
        ///Indicates the number of files that will be captured or applied.
        ///</summary>
        WIM_MSG_SETRANGE,
        ///<summary>
        ///Indicates the number of files that have been captured or applied.
        ///</summary>
        WIM_MSG_SETPOS,
        ///<summary>
        ///Indicates that a file has been either captured or applied.
        ///</summary>
        WIM_MSG_STEPIT,
        ///<summary>
        ///Enables the caller to prevent a file resource from being compressed during a capture.
        ///</summary>
        WIM_MSG_COMPRESS,
        ///<summary>
        ///Alerts the caller that an error has occurred while capturing or applying an image.
        ///</summary>
        WIM_MSG_ERROR,
        ///<summary>
        ///Enables the caller to align a file resource on a particular alignment boundary.
        ///</summary>
        WIM_MSG_ALIGNMENT,
        WIM_MSG_RETRY,
        ///<summary>
        ///Enables the caller to align a file resource on a particular alignment boundary.
        ///</summary>
        WIM_MSG_SPLIT,
        WIM_MSG_SUCCESS = 0x00000000,
        WIM_MSG_ABORT_IMAGE = 0xFFFFFFFF
    }
 
    internal enum
    WimCreationDisposition : uint
        {
        WimOpenExisting = 0x00000003,
    }
 
    internal enum
    WimActionFlags : uint
        {
        WimIgnored = 0x00000000
    }
 
    internal enum
    WimCompressionType : uint
        {
        WimIgnored = 0x00000000
    }
 
    internal enum
    WimCreationResult : uint
        {
        WimCreatedNew = 0x00000000,
        WimOpenedExisting = 0x00000001
    }
 
    #endregion WIMGAPI
 
    #endregion Enums and Flags
 
    #region Structs
 
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct CreateVirtualDiskParameters
    {
        /// <summary>
        /// A CREATE_VIRTUAL_DISK_VERSION enumeration that specifies the version of the CREATE_VIRTUAL_DISK_PARAMETERS structure being passed to or from the virtual hard disk (VHD) functions.
        /// </summary>
        public CreateVirtualDiskVersion Version;
 
        /// <summary>
        /// Unique identifier to assign to the virtual disk object. If this member is set to zero, a unique identifier is created by the system.
        /// </summary>
        public Guid UniqueId;
 
        /// <summary>
        /// The maximum virtual size of the virtual disk object. Must be a multiple of 512.
        /// If a ParentPath is specified, this value must be zero.
        /// If a SourcePath is specified, this value can be zero to specify the size of the source VHD to be used, otherwise the size specified must be greater than or equal to the size of the source disk.
        /// </summary>
        public ulong MaximumSize;
 
        /// <summary>
        /// Internal size of the virtual disk object blocks.
        /// The following are predefined block sizes and their behaviors. For a fixed VHD type, this parameter must be zero.
        /// </summary>
        public uint BlockSizeInBytes;
 
        /// <summary>
        /// Internal size of the virtual disk object sectors. Must be set to 512.
        /// </summary>
        public uint SectorSizeInBytes;
 
        /// <summary>
        /// Optional path to a parent virtual disk object. Associates the new virtual disk with an existing virtual disk.
        /// If this parameter is not NULL, SourcePath must be NULL.
        /// </summary>
        public string ParentPath;
 
        /// <summary>
        /// Optional path to pre-populate the new virtual disk object with block data from an existing disk. This path may refer to a VHD or a physical disk.
        /// If this parameter is not NULL, ParentPath must be NULL.
        /// </summary>
        public string SourcePath;
 
        /// <summary>
        /// Flags for opening the VHD
        /// </summary>
        public OpenVirtualDiskFlags OpenFlags;
 
        /// <summary>
        /// GetInfoOnly flag for V2 handles
        /// </summary>
        public bool GetInfoOnly;
 
        /// <summary>
        /// Virtual Storage Type of the parent disk
        /// </summary>
        public VirtualStorageType ParentVirtualStorageType;
 
        /// <summary>
        /// Virtual Storage Type of the source disk
        /// </summary>
        public VirtualStorageType SourceVirtualStorageType;
 
        /// <summary>
        /// A GUID to use for fallback resiliency over SMB.
        /// </summary>
        public Guid ResiliencyGuid;
    }
 
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct VirtualStorageType
    {
        public VirtualStorageDeviceType DeviceId;
        public Guid VendorId;
    }
 
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct SecurityDescriptor
    {
        public byte revision;
        public byte size;
        public short control;
        public IntPtr owner;
        public IntPtr group;
        public IntPtr sacl;
        public IntPtr dacl;
    }
 
    #endregion Structs
 
    #region VirtDisk.DLL P/Invoke
 
    [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
    public static extern uint
    CreateVirtualDisk(
        [In, Out] ref VirtualStorageType VirtualStorageType,
        [In] string Path,
        [In] VirtualDiskAccessMask VirtualDiskAccessMask,
        [In, Out] ref SecurityDescriptor SecurityDescriptor,
        [In] CreateVirtualDiskFlags Flags,
        [In] uint ProviderSpecificFlags,
        [In, Out] ref CreateVirtualDiskParameters Parameters,
        [In] IntPtr Overlapped,
        [Out] out SafeFileHandle Handle);
 
    #endregion VirtDisk.DLL P/Invoke
 
    #region Win32 P/Invoke
 
    [DllImport("advapi32", SetLastError = true)]
    public static extern bool InitializeSecurityDescriptor(
        [Out] out SecurityDescriptor pSecurityDescriptor,
        [In] uint dwRevision);
 
    #endregion Win32 P/Invoke
 
    #region WIMGAPI P/Invoke
 
    #region SafeHandle wrappers for WimFileHandle and WimImageHandle
 
    public sealed class WimFileHandle : SafeHandle
    {
 
        public WimFileHandle(
            string wimPath)
            : base(IntPtr.Zero, true)
            {
 
            if (String.IsNullOrEmpty(wimPath))
            {
                throw new ArgumentNullException("wimPath");
            }
 
            if (!File.Exists(Path.GetFullPath(wimPath)))
            {
                throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
            }
 
            NativeMethods.WimCreationResult creationResult;
 
            this.handle = NativeMethods.WimCreateFile(
                wimPath,
                NativeMethods.WimCreateFileDesiredAccess.WimGenericRead,
                NativeMethods.WimCreationDisposition.WimOpenExisting,
                NativeMethods.WimActionFlags.WimIgnored,
                NativeMethods.WimCompressionType.WimIgnored,
                out creationResult
            );
 
            // Check results.
            if (creationResult != NativeMethods.WimCreationResult.WimOpenedExisting)
            {
                throw new Win32Exception();
            }
 
            if (this.handle == IntPtr.Zero)
            {
                throw new Win32Exception();
            }
 
            // Set the temporary path.
            NativeMethods.WimSetTemporaryPath(
                this,
                Environment.ExpandEnvironmentVariables("%TEMP%")
            );
        }
 
        protected override bool ReleaseHandle()
        {
            return NativeMethods.WimCloseHandle(this.handle);
        }
 
        public override bool IsInvalid
        {
            get { return this.handle == IntPtr.Zero; }
        }
    }
 
    public sealed class WimImageHandle : SafeHandle
    {
        public WimImageHandle(
            WimFile Container,
            uint ImageIndex)
            : base(IntPtr.Zero, true)
            {
 
            if (null == Container)
            {
                throw new ArgumentNullException("Container");
            }
 
            if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid))
            {
                throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
            }
 
            if (ImageIndex > Container.ImageCount)
            {
                throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
            }
 
            this.handle = NativeMethods.WimLoadImage(
                Container.Handle.DangerousGetHandle(),
                ImageIndex);
        }
 
        protected override bool ReleaseHandle()
        {
            return NativeMethods.WimCloseHandle(this.handle);
        }
 
        public override bool IsInvalid
        {
            get { return this.handle == IntPtr.Zero; }
        }
    }
 
    #endregion SafeHandle wrappers for WimFileHandle and WimImageHandle
 
    [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCreateFile")]
    internal static extern IntPtr
    WimCreateFile(
        [In, MarshalAs(UnmanagedType.LPWStr)] string WimPath,
        [In] WimCreateFileDesiredAccess DesiredAccess,
        [In] WimCreationDisposition CreationDisposition,
        [In] WimActionFlags FlagsAndAttributes,
        [In] WimCompressionType CompressionType,
        [Out, Optional] out WimCreationResult CreationResult
    );
 
    [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCloseHandle")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool
    WimCloseHandle(
        [In] IntPtr Handle
    );
 
    [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMLoadImage")]
    internal static extern IntPtr
    WimLoadImage(
        [In] IntPtr Handle,
        [In] uint ImageIndex
    );
 
    [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageCount")]
    internal static extern uint
    WimGetImageCount(
        [In] WimFileHandle Handle
    );
 
    [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageInformation")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool
    WimGetImageInformation(
        [In] SafeHandle Handle,
        [Out] out StringBuilder ImageInfo,
        [Out] out uint SizeOfImageInfo
    );
 
    [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMSetTemporaryPath")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool
    WimSetTemporaryPath(
        [In] WimFileHandle Handle,
        [In] string TempPath
    );
 
    [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMRegisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
    internal static extern uint
    WimRegisterMessageCallback(
        [In, Optional] WimFileHandle hWim,
        [In] WimMessageCallback MessageProc,
        [In, Optional] IntPtr ImageInfo
    );
 
    [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMUnregisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool
    WimUnregisterMessageCallback(
        [In, Optional] WimFileHandle hWim,
        [In] WimMessageCallback MessageProc
    );
 
 
    #endregion WIMGAPI P/Invoke
}
 
#region WIM Interop
 
public class WimFile
{
 
    internal XDocument m_xmlInfo;
    internal List<WimImage> m_imageList;
 
    private static NativeMethods.WimMessageCallback wimMessageCallback;
 
    #region Events
 
    /// <summary>
    /// DefaultImageEvent handler
    /// </summary>
    public delegate void DefaultImageEventHandler(object sender, DefaultImageEventArgs e);
 
    ///<summary>
    ///ProcessFileEvent handler
    ///</summary>
    public delegate void ProcessFileEventHandler(object sender, ProcessFileEventArgs e);
 
    ///<summary>
    ///Enable the caller to prevent a file resource from being compressed during a capture.
    ///</summary>
    public event ProcessFileEventHandler ProcessFileEvent;
 
    ///<summary>
    ///Indicate an update in the progress of an image application.
    ///</summary>
    public event DefaultImageEventHandler ProgressEvent;
 
    ///<summary>
    ///Alert the caller that an error has occurred while capturing or applying an image.
    ///</summary>
    public event DefaultImageEventHandler ErrorEvent;
 
    ///<summary>
    ///Indicate that a file has been either captured or applied.
    ///</summary>
    public event DefaultImageEventHandler StepItEvent;
 
    ///<summary>
    ///Indicate the number of files that will be captured or applied.
    ///</summary>
    public event DefaultImageEventHandler SetRangeEvent;
 
    ///<summary>
    ///Indicate the number of files that have been captured or applied.
    ///</summary>
    public event DefaultImageEventHandler SetPosEvent;
 
    #endregion Events
 
    private
    enum
    ImageEventMessage : uint
    {
        ///<summary>
        ///Enables the caller to prevent a file or a directory from being captured or applied.
        ///</summary>
        Progress = NativeMethods.WimMessage.WIM_MSG_PROGRESS,
        ///<summary>
        ///Notification sent to enable the caller to prevent a file or a directory from being captured or applied.
        ///To prevent a file or a directory from being captured or applied, call WindowsImageContainer.SkipFile().
        ///</summary>
        Process = NativeMethods.WimMessage.WIM_MSG_PROCESS,
        ///<summary>
        ///Enables the caller to prevent a file resource from being compressed during a capture.
        ///</summary>
        Compress = NativeMethods.WimMessage.WIM_MSG_COMPRESS,
        ///<summary>
        ///Alerts the caller that an error has occurred while capturing or applying an image.
        ///</summary>
        Error = NativeMethods.WimMessage.WIM_MSG_ERROR,
        ///<summary>
        ///Enables the caller to align a file resource on a particular alignment boundary.
        ///</summary>
        Alignment = NativeMethods.WimMessage.WIM_MSG_ALIGNMENT,
        ///<summary>
        ///Enables the caller to align a file resource on a particular alignment boundary.
        ///</summary>
        Split = NativeMethods.WimMessage.WIM_MSG_SPLIT,
        ///<summary>
        ///Indicates that volume information is being gathered during an image capture.
        ///</summary>
        Scanning = NativeMethods.WimMessage.WIM_MSG_SCANNING,
        ///<summary>
        ///Indicates the number of files that will be captured or applied.
        ///</summary>
        SetRange = NativeMethods.WimMessage.WIM_MSG_SETRANGE,
        ///<summary>
        ///Indicates the number of files that have been captured or applied.
        /// </summary>
        SetPos = NativeMethods.WimMessage.WIM_MSG_SETPOS,
        ///<summary>
        ///Indicates that a file has been either captured or applied.
        ///</summary>
        StepIt = NativeMethods.WimMessage.WIM_MSG_STEPIT,
        ///<summary>
        ///Success.
        ///</summary>
        Success = NativeMethods.WimMessage.WIM_MSG_SUCCESS,
        ///<summary>
        ///Abort.
        ///</summary>
        Abort = NativeMethods.WimMessage.WIM_MSG_ABORT_IMAGE
    }
 
    ///<summary>
    ///Event callback to the Wimgapi events
    ///</summary>
    private
    uint
    ImageEventMessagePump(
        uint MessageId,
        IntPtr wParam,
        IntPtr lParam,
        IntPtr UserData)
        {
 
        uint status = (uint) NativeMethods.WimMessage.WIM_MSG_SUCCESS;
 
        DefaultImageEventArgs eventArgs = new DefaultImageEventArgs(wParam, lParam, UserData);
 
        switch ((ImageEventMessage)MessageId)
        {
 
            case ImageEventMessage.Progress:
                ProgressEvent(this, eventArgs);
                break;
 
            case ImageEventMessage.Process:
                if (null != ProcessFileEvent)
                {
                    string fileToImage = Marshal.PtrToStringUni(wParam);
                    ProcessFileEventArgs fileToProcess = new ProcessFileEventArgs(fileToImage, lParam);
                    ProcessFileEvent(this, fileToProcess);
 
                    if (fileToProcess.Abort == true)
                    {
                        status = (uint)ImageEventMessage.Abort;
                    }
                }
                break;
 
            case ImageEventMessage.Error:
                if (null != ErrorEvent)
                {
                    ErrorEvent(this, eventArgs);
                }
                break;
 
            case ImageEventMessage.SetRange:
                if (null != SetRangeEvent)
                {
                    SetRangeEvent(this, eventArgs);
                }
                break;
 
            case ImageEventMessage.SetPos:
                if (null != SetPosEvent)
                {
                    SetPosEvent(this, eventArgs);
                }
                break;
 
            case ImageEventMessage.StepIt:
                if (null != StepItEvent)
                {
                    StepItEvent(this, eventArgs);
                }
                break;
 
            default:
                break;
        }
        return status;
 
    }
 
    /// <summary>
    /// Constructor.
    /// </summary>
    /// <param name="wimPath">Path to the WIM container.</param>
    public
    WimFile(string wimPath)
    {
        if (string.IsNullOrEmpty(wimPath))
        {
            throw new ArgumentNullException("wimPath");
        }
 
        if (!File.Exists(Path.GetFullPath(wimPath)))
        {
            throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
        }
 
        Handle = new NativeMethods.WimFileHandle(wimPath);
 
        // Hook up the events before we return.
        //wimMessageCallback = new NativeMethods.WimMessageCallback(ImageEventMessagePump);
        //NativeMethods.RegisterMessageCallback(this.Handle, wimMessageCallback);
    }
 
    /// <summary>
    /// Closes the WIM file.
    /// </summary>
    public void
    Close()
    {
        foreach (WimImage image in Images)
        {
            image.Close();
        }
 
        if (null != wimMessageCallback)
        {
            NativeMethods.UnregisterMessageCallback(this.Handle, wimMessageCallback);
            wimMessageCallback = null;
        }
 
        if ((!Handle.IsClosed) && (!Handle.IsInvalid))
        {
            Handle.Close();
        }
    }
 
    /// <summary>
    /// Provides a list of WimImage objects, representing the images in the WIM container file.
    /// </summary>
    public List<WimImage>
    Images
    {
        get
        {
            if (null == m_imageList)
            {
 
                int imageCount = (int)ImageCount;
                m_imageList = new List<WimImage>(imageCount);
                for (int i = 0; i < imageCount; i++)
                {
 
                    // Load up each image so it's ready for us.
                    m_imageList.Add(
                        new WimImage(this, (uint)i + 1));
                }
            }
 
            return m_imageList;
        }
    }
 
    /// <summary>
    /// Provides a list of names of the images in the specified WIM container file.
    /// </summary>
    public List<string>
    ImageNames
    {
        get
        {
            List<string> nameList = new List<string>();
            foreach (WimImage image in Images)
            {
                nameList.Add(image.ImageName);
            }
            return nameList;
        }
    }
 
    /// <summary>
    /// Indexer for WIM images inside the WIM container, indexed by the image number.
    /// The list of Images is 0-based, but the WIM container is 1-based, so we automatically compensate for that.
    /// this[1] returns the 0th image in the WIM container.
    /// </summary>
    /// <param name="ImageIndex">The 1-based index of the image to retrieve.</param>
    /// <returns>WinImage object.</returns>
    public WimImage
    this[int ImageIndex]
    {
        get { return Images[ImageIndex - 1]; }
    }
 
    /// <summary>
    /// Indexer for WIM images inside the WIM container, indexed by the image name.
    /// WIMs created by different processes sometimes contain different information - including the name.
    /// Some images have their name stored in the Name field, some in the Flags field, and some in the EditionID field.
    /// We take all of those into account in while searching the WIM.
    /// </summary>
    /// <param name="ImageName"></param>
    /// <returns></returns>
    public WimImage
    this[string ImageName]
    {
        get
        {
            return
                Images.Where(i => (
                    i.ImageName.ToUpper() == ImageName.ToUpper() ||
                    i.ImageFlags.ToUpper() == ImageName.ToUpper() ))
                .DefaultIfEmpty(null)
                    .FirstOrDefault<WimImage>();
        }
    }
 
    /// <summary>
    /// Returns the number of images in the WIM container.
    /// </summary>
    internal uint
    ImageCount
    {
        get { return NativeMethods.WimGetImageCount(Handle); }
    }
 
    /// <summary>
    /// Returns an XDocument representation of the XML metadata for the WIM container and associated images.
    /// </summary>
    internal XDocument
    XmlInfo
    {
        get
        {
 
            if (null == m_xmlInfo)
            {
                StringBuilder builder;
                uint bytes;
                if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes))
                {
                    throw new Win32Exception();
                }
 
                // Ensure the length of the returned bytes to avoid garbage characters at the end.
                int charCount = (int)bytes / sizeof(char);
                if (null != builder)
                {
                    // Get rid of the unicode file marker at the beginning of the XML.
                    builder.Remove(0, 1);
                    builder.EnsureCapacity(charCount - 1);
                    builder.Length = charCount - 1;
 
                    // This isn't likely to change while we have the image open, so cache it.
                    m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
                }
                else
                {
                    m_xmlInfo = null;
                }
            }
 
            return m_xmlInfo;
        }
    }
 
    public NativeMethods.WimFileHandle Handle
    {
        get;
        private set;
    }
}
 
public class
WimImage
{
 
    internal XDocument m_xmlInfo;
 
    public
    WimImage(
        WimFile Container,
        uint ImageIndex)
        {
 
        if (null == Container)
        {
            throw new ArgumentNullException("Container");
        }
 
        if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid))
        {
            throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
        }
 
        if (ImageIndex > Container.ImageCount)
        {
            throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
        }
 
        Handle = new NativeMethods.WimImageHandle(Container, ImageIndex);
    }
 
    public enum
    Architectures : uint
    {
        x86 = 0x0,
        ARM = 0x5,
        IA64 = 0x6,
        AMD64 = 0x9,
        ARM64 = 0xC
    }
 
    public void
    Close()
    {
        if ((!Handle.IsClosed) && (!Handle.IsInvalid))
        {
            Handle.Close();
        }
    }
 
    public NativeMethods.WimImageHandle
    Handle
    {
        get;
        private set;
    }
 
    internal XDocument
    XmlInfo
    {
        get
        {
 
            if (null == m_xmlInfo)
            {
                StringBuilder builder;
                uint bytes;
                if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes))
                {
                    throw new Win32Exception();
                }
 
                // Ensure the length of the returned bytes to avoid garbage characters at the end.
                int charCount = (int)bytes / sizeof(char);
                if (null != builder)
                {
                    // Get rid of the unicode file marker at the beginning of the XML.
                    builder.Remove(0, 1);
                    builder.EnsureCapacity(charCount - 1);
                    builder.Length = charCount - 1;
 
                    // This isn't likely to change while we have the image open, so cache it.
                    m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
                }
                else
                {
                    m_xmlInfo = null;
                }
            }
 
            return m_xmlInfo;
        }
    }
 
    public string
    ImageIndex
    {
        get { return XmlInfo.Element("IMAGE").Attribute("INDEX").Value; }
    }
 
    public string
    ImageName
    {
        get { return XmlInfo.XPathSelectElement("/IMAGE/NAME").Value; }
    }
 
    public string
    ImageEditionId
    {
        get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/EDITIONID").Value; }
    }
 
    public string
    ImageFlags
    {
        get
        {
            string flagValue = String.Empty;
 
            try
            {
                flagValue = XmlInfo.XPathSelectElement("/IMAGE/FLAGS").Value;
            }
            catch
            {
 
                // Some WIM files don't contain a FLAGS element in the metadata.
                // In an effort to support those WIMs too, inherit the EditionId if there
                // are no Flags.
 
                if (String.IsNullOrEmpty(flagValue))
                {
                    flagValue = this.ImageEditionId;
 
                    // Check to see if the EditionId is "ServerHyper". If so,
                    // tweak it to be "ServerHyperCore" instead.
 
                    if (0 == String.Compare("serverhyper", flagValue, true))
                    {
                        flagValue = "ServerHyperCore";
                    }
                }
 
            }
 
            return flagValue;
        }
    }
 
    public string
    ImageProductType
    {
        get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/PRODUCTTYPE").Value; }
    }
 
    public string
    ImageInstallationType
    {
        get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/INSTALLATIONTYPE").Value; }
    }
 
    public string
    ImageDescription
    {
        get { return XmlInfo.XPathSelectElement("/IMAGE/DESCRIPTION").Value; }
    }
 
    public ulong
    ImageSize
    {
        get { return ulong.Parse(XmlInfo.XPathSelectElement("/IMAGE/TOTALBYTES").Value); }
    }
 
    public Architectures
    ImageArchitecture
    {
        get
        {
            int arch = -1;
            try
            {
                arch = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/ARCH").Value);
            }
            catch { }
 
            return (Architectures)arch;
        }
    }
 
    public string
    ImageDefaultLanguage
    {
        get
        {
            string lang = null;
            try
            {
                lang = XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/LANGUAGES/DEFAULT").Value;
            }
            catch { }
 
            return lang;
        }
    }
 
    public Version
    ImageVersion
    {
        get
        {
            int major = 0;
            int minor = 0;
            int build = 0;
            int revision = 0;
 
            try
            {
                major = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MAJOR").Value);
                minor = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MINOR").Value);
                build = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/BUILD").Value);
                revision = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/SPBUILD").Value);
            }
            catch { }
 
            return (new Version(major, minor, build, revision));
        }
    }
 
    public string
    ImageDisplayName
    {
        get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYNAME").Value; }
    }
 
    public string
    ImageDisplayDescription
    {
        get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYDESCRIPTION").Value; }
    }
}
 
///<summary>
///Describes the file that is being processed for the ProcessFileEvent.
///</summary>
public class
DefaultImageEventArgs : EventArgs
{
    ///<summary>
    ///Default constructor.
    ///</summary>
    public
    DefaultImageEventArgs(
        IntPtr wideParameter,
        IntPtr leftParameter,
        IntPtr userData)
    {
 
        WideParameter = wideParameter;
        LeftParameter = leftParameter;
        UserData = userData;
    }
 
    ///<summary>
    ///wParam
    ///</summary>
    public IntPtr WideParameter
    {
        get;
        private set;
    }
 
    ///<summary>
    ///lParam
    ///</summary>
    public IntPtr LeftParameter
    {
        get;
        private set;
    }
 
    ///<summary>
    ///UserData
    ///</summary>
    public IntPtr UserData
    {
        get;
        private set;
    }
}
 
///<summary>
///Describes the file that is being processed for the ProcessFileEvent.
///</summary>
public class
ProcessFileEventArgs : EventArgs
{
    ///<summary>
    ///Default constructor.
    ///</summary>
    ///<param name="file">Fully qualified path and file name. For example: c:\file.sys.</param>
    ///<param name="skipFileFlag">Default is false - skip file and continue.
    ///Set to true to abort the entire image capture.</param>
    public
    ProcessFileEventArgs(
        string file,
        IntPtr skipFileFlag)
        {
 
        m_FilePath = file;
        m_SkipFileFlag = skipFileFlag;
    }
 
    ///<summary>
    ///Skip file from being imaged.
    ///</summary>
    public void
    SkipFile()
    {
        byte[] byteBuffer =
        {
                0
        };
        int byteBufferSize = byteBuffer.Length;
        Marshal.Copy(byteBuffer, 0, m_SkipFileFlag, byteBufferSize);
    }
 
    ///<summary>
    ///Fully qualified path and file name.
    ///</summary>
    public string
    FilePath
    {
        get
        {
            string stringToReturn = "";
            if (m_FilePath != null)
            {
                stringToReturn = m_FilePath;
            }
            return stringToReturn;
        }
    }
 
    ///<summary>
    ///Flag to indicate if the entire image capture should be aborted.
    ///Default is false - skip file and continue. Setting to true will
    ///abort the entire image capture.
    ///</summary>
    public bool Abort
    {
        set { m_Abort = value; }
        get { return m_Abort; }
    }
 
    private string m_FilePath;
    private bool m_Abort;
    private IntPtr m_SkipFileFlag;
 
}
 
#endregion WIM Interop
 
#region VHD Interop
// Based on code written by the Hyper-V Test team.
/// <summary>
/// The Virtual Hard Disk class provides methods for creating and manipulating Virtual Hard Disk files.
/// </summary>
public class
VirtualHardDisk
{
    #region Static Methods
 
    #region Sparse Disks
 
    /// <summary>
    /// Abbreviated signature of CreateSparseDisk so it's easier to use from WIM2VHD.
    /// </summary>
    /// <param name="virtualStorageDeviceType">The type of disk to create, VHD or VHDX.</param>
    /// <param name="path">The path of the disk to create.</param>
    /// <param name="size">The maximum size of the disk to create.</param>
    /// <param name="overwrite">Overwrite the VHD if it already exists.</param>
    public static void
    CreateSparseDisk(
        NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
        string path,
        ulong size,
        bool overwrite)
        {
 
        CreateSparseDisk(
            path,
            size,
            overwrite,
            null,
            IntPtr.Zero,
            (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
                ? NativeMethods.DEFAULT_BLOCK_SIZE
                : 0,
            virtualStorageDeviceType,
            NativeMethods.DISK_SECTOR_SIZE);
    }
 
    /// <summary>
    /// Creates a new sparse (dynamically expanding) virtual hard disk (.vhd). Supports both sync and async modes.
    /// The VHD image file uses only as much space on the backing store as needed to store the actual data the VHD currently contains.
    /// </summary>
    /// <param name="path">The path and name of the VHD to create.</param>
    /// <param name="size">The size of the VHD to create in bytes.
    /// When creating this type of VHD, the VHD API does not test for free space on the physical backing store based on the maximum size requested,
    /// therefore it is possible to successfully create a dynamic VHD with a maximum size larger than the available physical disk free space.
    /// The maximum size of a dynamic VHD is 2,040 GB. The minimum size is 3 MB.</param>
    /// <param name="source">Optional path to pre-populate the new virtual disk object with block data from an existing disk
    /// This path may refer to a VHD or a physical disk. Use NULL if you don't want a source.</param>
    /// <param name="overwrite">If the VHD exists, setting this parameter to 'True' will delete it and create a new one.</param>
    /// <param name="overlapped">If not null, the operation runs in async mode</param>
    /// <param name="blockSizeInBytes">Block size for the VHD.</param>
    /// <param name="virtualStorageDeviceType">VHD format version (VHD1 or VHD2)</param>
    /// <param name="sectorSizeInBytes">Sector size for the VHD.</param>
    /// <exception cref="ArgumentOutOfRangeException">Thrown when an invalid size is specified</exception>
    /// <exception cref="FileNotFoundException">Thrown when source VHD is not found.</exception>
    /// <exception cref="SecurityException">Thrown when there was an error while creating the default security descriptor.</exception>
    /// <exception cref="Win32Exception">Thrown when an error occurred while creating the VHD.</exception>
    public static void
    CreateSparseDisk(
        string path,
        ulong size,
        bool overwrite,
        string source,
        IntPtr overlapped,
        uint blockSizeInBytes,
        NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
        uint sectorSizeInBytes)
        {
 
        // Validate the virtualStorageDeviceType
        if (virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHD && virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHDX)
        {
 
            throw (
                new ArgumentOutOfRangeException(
                    "virtualStorageDeviceType",
                    virtualStorageDeviceType,
                    "VirtualStorageDeviceType must be VHD or VHDX."
            ));
        }
 
        // Validate size. It needs to be a multiple of DISK_SECTOR_SIZE (512)...
        if ((size % NativeMethods.DISK_SECTOR_SIZE) != 0)
        {
 
            throw (
                new ArgumentOutOfRangeException(
                    "size",
                    size,
                    "The size of the virtual disk must be a multiple of 512."
            ));
        }
 
        if ((!String.IsNullOrEmpty(source)) && (!System.IO.File.Exists(source)))
        {
 
            throw (
                new System.IO.FileNotFoundException(
                    "Unable to find the source file.",
                    source
            ));
        }
 
        if ((overwrite) && (System.IO.File.Exists(path)))
        {
 
            System.IO.File.Delete(path);
        }
 
        NativeMethods.CreateVirtualDiskParameters createParams = new NativeMethods.CreateVirtualDiskParameters();
 
        // Select the correct version.
        createParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
            ? NativeMethods.CreateVirtualDiskVersion.Version1
            : NativeMethods.CreateVirtualDiskVersion.Version2;
 
        createParams.UniqueId = Guid.NewGuid();
        createParams.MaximumSize = size;
        createParams.BlockSizeInBytes = blockSizeInBytes;
        createParams.SectorSizeInBytes = sectorSizeInBytes;
        createParams.ParentPath = null;
        createParams.SourcePath = source;
        createParams.OpenFlags = NativeMethods.OpenVirtualDiskFlags.None;
        createParams.GetInfoOnly = false;
        createParams.ParentVirtualStorageType = new NativeMethods.VirtualStorageType();
        createParams.SourceVirtualStorageType = new NativeMethods.VirtualStorageType();
 
        //
        // Create and init a security descriptor.
        // Since we're creating an essentially blank SD to use with CreateVirtualDisk
        // the VHD will take on the security values from the parent directory.
        //
 
        NativeMethods.SecurityDescriptor securityDescriptor;
        if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1))
        {
 
            throw (
                new SecurityException(
                    "Unable to initialize the security descriptor for the virtual disk."
            ));
        }
 
        NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType();
        virtualStorageType.DeviceId = virtualStorageDeviceType;
        virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft;
 
        SafeFileHandle vhdHandle;
 
        uint returnCode = NativeMethods.CreateVirtualDisk(
            ref virtualStorageType,
                path,
                (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
                    ? NativeMethods.VirtualDiskAccessMask.All
                    : NativeMethods.VirtualDiskAccessMask.None,
            ref securityDescriptor,
                NativeMethods.CreateVirtualDiskFlags.None,
                0,
            ref createParams,
                overlapped,
            out vhdHandle);
 
        vhdHandle.Close();
 
        if (NativeMethods.ERROR_SUCCESS != returnCode && NativeMethods.ERROR_IO_PENDING != returnCode)
        {
 
            throw (
                new Win32Exception(
                    (int)returnCode
            ));
        }
    }
 
    #endregion Sparse Disks
 
    #endregion Static Methods
 
}
#endregion VHD Interop
}
"@


    Add-Type -TypeDefinition $code -ReferencedAssemblies "System.Xml","System.Linq","System.Xml.Linq" -ErrorAction SilentlyContinue
}