forked from jamesstringerparsec/Easy-GPU-PV
-
Notifications
You must be signed in to change notification settings - Fork 1
/
CopyFilesToVM.ps1
4409 lines (3744 loc) · 170 KB
/
CopyFilesToVM.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
$params = @{
VMName = "GPUPV"
SourcePath = "C:\Users\james\Downloads\Win11_English_x64.iso"
Edition = 6
VhdFormat = "VHDX"
DiskLayout = "UEFI"
SizeBytes = 40GB
MemoryAmount = 8GB
CPUCores = 4
NetworkSwitch = "Default Switch"
VHDPath = "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\"
UnattendPath = "$PSScriptRoot"+"\autounattend.xml"
MergeFolder = "$PSScriptRoot"+"\CopyToRootC\"
GPUName = "AUTO"
GPUResourceAllocationPercentage = 25
Team_ID = ""
Key = ""
Username = "GPUVM"
Password = "CoolestPassword!"
Autologon = "true"
}
Import-Module $PSSCriptRoot\Add-VMGpuPartitionAdapterFiles.psm1
function Is-Administrator
{
$CurrentUser = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $CurrentUser).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
Function Dismount-ISO {
param (
[string]$SourcePath
)
$disk = Get-Volume | Where-Object {$_.DriveType -eq "CD-ROM"} | select *
Foreach ($d in $disk) {
Dismount-DiskImage -ImagePath $sourcePath | Out-Null
}
}
Function Mount-ISOReliable {
param (
[string]$SourcePath
)
$mountResult = Mount-DiskImage -ImagePath $SourcePath
$delay = 0
Do {
if ($delay -gt 15) {
Function Get-NewDriveLetter {
$UsedDriveLetters = ((Get-Volume).DriveLetter) -join ""
Do {
$DriveLetter = (65..90)| Get-Random | % {[char]$_}
}
Until (!$UsedDriveLetters.Contains("$DriveLetter"))
$DriveLetter
}
$DriveLetter = "$(Get-NewDriveLetter)" + ":"
Get-WmiObject -Class Win32_volume | Where-Object {$_.Label -eq "CCCOMA_X64FRE_EN-US_DV9"} | Set-WmiInstance -Arguments @{DriveLetter="$driveletter"}
}
Start-Sleep -s 1
$delay++
}
Until (($mountResult | Get-Volume).DriveLetter -ne $NULL)
($mountResult | Get-Volume).DriveLetter
}
Function ConcatenateVHDPath {
param(
[string]$VHDPath,
[string]$VMName
)
if ($VHDPath[-1] -eq '\') {
$VHDPath + $VMName + ".vhdx"
}
Else {
$VHDPath + "\" + $VMName + ".vhdx"
}
}
Function SmartExit {
param (
[switch]$NoHalt,
[string]$ExitReason
)
if (($host.name -eq 'Windows PowerShell ISE Host') -or ($host.Name -eq 'Visual Studio Code Host')) {
Write-Host $ExitReason
Exit
}
else{
if ($NoHalt) {
Write-Host $ExitReason
Exit
}
else {
Write-Host $ExitReason
Read-host -Prompt "Press any key to Exit..."
Exit
}
}
}
Function Check-Params {
$ExitReason = @()
if ([ENVIRONMENT]::Is64BitProcess -eq $false) {
$ExitReason += "You are not using the correct version of Powershell, do not use Powershell(x86)."
}
if ((Is-Administrator) -eq $false) {
$ExitReason += "Script not running as Administrator, please run script as Administrator."
}
if (!(Test-Path $params.VHDPath)) {
$ExitReason += "VHDPath Directory doesn't exist, please create it before running this script."
}
if (!(test-path $params.SourcePath)) {
$ExitReason += "ISO Path Invalid. Please enter a valid ISO Path in the SourcePath section of Params."
}
else {
$ISODriveLetter = Mount-ISOReliable -SourcePath $params.SourcePath
if (!(Test-Path $("$ISODriveLetter"+":\Sources\install.wim"))) {
$ExitReason += "This ISO is invalid, please check readme for ISO downloading instructions."
}
Dismount-ISO -SourcePath $params.SourcePath
}
if ($params.Username -eq $params.VMName ) {
$ExitReason += "Username cannot be the same as VMName."
}
if (!($params.Username -match "^[a-zA-Z0-9]+$")) {
$ExitReason += "Username cannot contain special characters."
}
if (($params.VMName -notmatch "^[a-zA-Z0-9]+$") -or ($params.VMName.Length -gt 15)) {
$ExitReason += "VMName cannot contain special characters, or be more than 15 characters long"
}
if (([Environment]::OSVersion.Version.Build -lt 22000) -and ($params.GPUName -ne "AUTO")) {
$ExitReason += "GPUName must be set to AUTO on Windows 10."
}
If ($ExitReason.Count -gt 0) {
Write-Host "Script failed params check due to the following reasons:" -ForegroundColor DarkYellow
ForEach ($IndividualReason in $ExitReason) {
Write-Host "ERROR: $IndividualReason" -ForegroundColor RED
}
SmartExit
}
}
Function Setup-ParsecInstall {
param(
[string]$DriveLetter,
[string]$Team_ID,
[string]$Key
)
$new = @()
$content = get-content "$PSScriptRoot\user\psscripts.ini"
foreach ($line in $content) {
if ($line -like "0Parameters="){
$line = "0Parameters=$Team_ID $Key"
$new += $line
}
Else {
$new += $line
}
}
Set-Content -Value $new -Path "$PSScriptRoot\user\psscripts.ini"
if((Test-Path -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon) -eq $true) {} Else {New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon -ItemType directory | Out-Null}
if((Test-Path -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logoff) -eq $true) {} Else {New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logoff -ItemType directory | Out-Null}
if((Test-Path -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Startup) -eq $true) {} Else {New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Startup -ItemType directory | Out-Null}
if((Test-Path -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Shutdown) -eq $true) {} Else {New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Shutdown -ItemType directory | Out-Null}
if((Test-Path -Path $DriveLetter\ProgramData\Easy-GPU-P) -eq $true) {} Else {New-Item -Path $DriveLetter\ProgramData\Easy-GPU-P -ItemType directory | Out-Null}
Copy-Item -Path $psscriptroot\VMScripts\VDDMonitor.ps1 -Destination $DriveLetter\ProgramData\Easy-GPU-P
Copy-Item -Path $psscriptroot\VMScripts\VBCableInstall.ps1 -Destination $DriveLetter\ProgramData\Easy-GPU-P
Copy-Item -Path $psscriptroot\VMScripts\ParsecVDDInstall.ps1 -Destination $DriveLetter\ProgramData\Easy-GPU-P
Copy-Item -Path $psscriptroot\VMScripts\ParsecPublic.cer -Destination $DriveLetter\ProgramData\Easy-GPU-P
Copy-Item -Path $psscriptroot\VMScripts\Parsec.lnk -Destination $DriveLetter\ProgramData\Easy-GPU-P
Copy-Item -Path $psscriptroot\gpt.ini -Destination $DriveLetter\Windows\system32\GroupPolicy
Copy-Item -Path $psscriptroot\User\psscripts.ini -Destination $DriveLetter\Windows\system32\GroupPolicy\User\Scripts
Copy-Item -Path $psscriptroot\User\Install.ps1 -Destination $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon
Copy-Item -Path $psscriptroot\Machine\psscripts.ini -Destination $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts
Copy-Item -Path $psscriptroot\Machine\Install.ps1 -Destination $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Startup
}
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
#>
[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")]
[Alias("DriveLetter")]
[string]
[ValidateNotNullOrEmpty()]
[string]$ISODriveLetter,
[Parameter(ParameterSetName="SRC")]
[Alias("GPU")]
[string]
[ValidateNotNullOrEmpty()]
[string]$GPUName,
[Parameter(ParameterSetName="SRC")]
[Alias("TeamID")]
[string]
#[ValidateNotNullOrEmpty()]
[string]$Team_ID,
[Parameter(ParameterSetName="SRC")]
[Alias("Teamkey")]
[string]
#[ValidateNotNullOrEmpty()]
[string]$Key,
[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