-
Notifications
You must be signed in to change notification settings - Fork 64
/
Convert-WindowsImage.ps1
4565 lines (3761 loc) · 197 KB
/
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
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 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.:
8250.0.amd64chk.winmain_win8beta.120217-1520_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 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 VHD.
.PARAMETER VHDType
Specifies whether to create a fixed (fully allocated) VHD(X) or a dynamic (sparse) VHD(X).
The default is dynamic.
.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 VHDPartitionStyle
Partition style (MBR or GPT) for the newly created disk (VHDX or VHD). By default
it will be partitioned with MBR partition style, used for older BIOS-based computers
and Generation 1 Virtual Machines in Hyper-V. For modern UEFI-based computers
and Generation 2 Virtual Machines, GPT partition layout is required.
.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.
.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
#>
#region Data
[CmdletBinding(DefaultParameterSetName="SRC",
HelpURI="http://gallery.technet.microsoft.com/scriptcenter/Convert-WindowsImageps1-0fe23a8f")]
param(
[Parameter(ParameterSetName="SRC", Mandatory=$true, ValueFromPipeline=$true)]
[Alias("WIM")]
[string]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path $(Resolve-Path $_) })]
$SourcePath,
[Parameter(ParameterSetName="SRC")]
[Alias("SKU")]
[string[]]
[ValidateNotNullOrEmpty()]
$Edition,
[Parameter(ParameterSetName="SRC")]
[Alias("WorkDir")]
[string]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path $_ })]
$WorkingDirectory = $pwd,
[Parameter(ParameterSetName="SRC")]
[Alias("VHD")]
[string]
[ValidateNotNullOrEmpty()]
$VHDPath,
[Parameter(ParameterSetName="SRC")]
[Alias("Size")]
[UInt64]
[ValidateNotNullOrEmpty()]
[ValidateRange(512MB, 64TB)]
$SizeBytes = 40GB,
[Parameter(ParameterSetName="SRC")]
[Alias("Format")]
[string]
[ValidateNotNullOrEmpty()]
[ValidateSet("VHD", "VHDX")]
$VHDFormat = "VHDX",
[Parameter(ParameterSetName="SRC")]
[Alias("DiskType")]
[string]
[ValidateNotNullOrEmpty()]
[ValidateSet("Dynamic", "Fixed")]
$VHDType = "Dynamic",
[Parameter(ParameterSetName="SRC")]
[string]
[ValidateNotNullOrEmpty()]
[ValidateSet("MBR", "GPT")]
$VHDPartitionStyle = "GPT",
[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="UI")]
[switch]
$ShowUI
)
#endregion Data
#region Code
# Begin Dynamic Parameters
# Create the parameters for the various types of debugging.
DynamicParam {
# 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 -Path "Variable:\EnableDebugger"
)
{
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)
break
#endregion BaudRate
}
"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)
break
#endregion NewKey
}
# 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 = 9000
QFE = 0
Branch = fbl_core1_hyp_dev(mikekol)
Timestamp = 141224-3000
Flavor = amd64fre
"@
}
# $vQuality = "Release to Web"
$vQuality = "Beta"
$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 = "$($env:Temp)\$($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 = 8250 # 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
##########################################################################################
# Text used for flag file embedded in VHD(X)
$flagText = @"
This $VHDFormat was created by Convert-WindowsImage.ps1 $myVersion $vQuality
on $([DateTime]::Now).
"@
# 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 $vQuality
"@
# 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!
"@
$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
}
/// <summary>
/// Specifies how the file is to be treated and what features are to be used.
/// </summary>
[FlagsAttribute]
internal enum
WimApplyFlags
: uint {
/// <summary>
/// No flags.
/// </summary>
WimApplyFlagsNone = 0x00000000,
/// <summary>
/// Reserved.
/// </summary>
WimApplyFlagsReserved = 0x00000001,
/// <summary>
/// Verifies that files match original data.
/// </summary>
WimApplyFlagsVerify = 0x00000002,
/// <summary>
/// Specifies that the image is to be sequentially read for caching or performance purposes.
/// </summary>
WimApplyFlagsIndex = 0x00000004,
/// <summary>
/// Applies the image without physically creating directories or files. Useful for obtaining a list of files and directories in the image.
/// </summary>
WimApplyFlagsNoApply = 0x00000008,
/// <summary>
/// Disables restoring security information for directories.
/// </summary>
WimApplyFlagsNoDirAcl = 0x00000010,
/// <summary>
/// Disables restoring security information for files
/// </summary>
WimApplyFlagsNoFileAcl = 0x00000020,
/// <summary>
/// The .wim file is opened in a mode that enables simultaneous reading and writing.
/// </summary>
WimApplyFlagsShareWrite = 0x00000040,
/// <summary>
/// Sends a WIM_MSG_FILEINFO message during the apply operation.
/// </summary>
WimApplyFlagsFileInfo = 0x00000080,
/// <summary>
/// Disables automatic path fixups for junctions and symbolic links.
/// </summary>
WimApplyFlagsNoRpFix = 0x00000100,
/// <summary>
/// Returns a handle that cannot commit changes, regardless of the access level requested at mount time.