forked from cloudbase/windows-imaging-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWinImageBuilder.psm1
executable file
·524 lines (464 loc) · 18.2 KB
/
WinImageBuilder.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 2
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$localResourcesDir = "$scriptPath\UnattendResources"
. "$scriptPath\Interop.ps1"
Import-Module dism
function ExecRetry($command, $maxRetryCount=4, $retryInterval=4)
{
$currErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "Continue"
$retryCount = 0
while ($true)
{
try
{
$res = Invoke-Command -ScriptBlock $command
$ErrorActionPreference = $currErrorActionPreference
return $res
}
catch [System.Exception]
{
$retryCount++
if ($retryCount -ge $maxRetryCount)
{
$ErrorActionPreference = $currErrorActionPreference
throw
}
else
{
if($_) {
Write-Warning $_
}
Start-Sleep $retryInterval
}
}
}
}
function CheckIsAdmin()
{
$wid = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$prp = new-object System.Security.Principal.WindowsPrincipal($wid)
$adm = [System.Security.Principal.WindowsBuiltInRole]::Administrator
$isAdmin = $prp.IsInRole($adm)
if(!$isAdmin)
{
throw "This cmdlet must be executed in an elevated administrative shell"
}
}
function Get-WimFileImagesInfo
{
[CmdletBinding()]
param
(
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]$WimFilePath = "D:\Sources\install.wim"
)
PROCESS
{
$w = new-object WIMInterop.WimFile -ArgumentList $WimFilePath
return $w.Images
}
}
function CreateImageVirtualDisk($vhdPath, $size, $diskLayout)
{
$v = [WIMInterop.VirtualDisk]::CreateVirtualDisk($vhdPath, $size)
try
{
$v.AttachVirtualDisk()
$path = $v.GetVirtualDiskPhysicalPath()
$m = $path -match "\\\\.\\PHYSICALDRIVE(?<num>\d+)"
$diskNum = $matches["num"]
$volumeLabel = "OS"
if($diskLayout -eq "UEFI")
{
Initialize-Disk -Number $diskNum -PartitionStyle GPT
# EFI partition
$systemPart = New-Partition -DiskNumber $diskNum -Size 200MB -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' -AssignDriveLetter
& format.com "$($systemPart.DriveLetter):" /FS:FAT32 /Q /Y | Out-Null
if($LASTEXITCODE) { throw "format failed" }
# MSR partition
$reservedPart = New-Partition -DiskNumber $diskNum -Size 128MB -GptType '{e3c9e316-0b5c-4db8-817d-f92df00215ae}'
# Windows partition
$windowsPart = New-Partition -DiskNumber $diskNum -UseMaximumSize -GptType "{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}" -AssignDriveLetter
}
else # BIOS
{
Initialize-Disk -Number $diskNum -PartitionStyle MBR
$windowsPart = New-Partition -DiskNumber $diskNum -UseMaximumSize -AssignDriveLetter -IsActive
$systemPart = $windowsPart
}
$format = Format-Volume -DriveLetter $windowsPart.DriveLetter -FileSystem NTFS -NewFileSystemLabel $volumeLabel -Force -Confirm:$false
return @("$($systemPart.DriveLetter):", "$($windowsPart.DriveLetter):")
}
finally
{
$v.Close()
}
}
function ApplyImage($winImagePath, $wimFilePath, $imageIndex)
{
Write-Output ('Applying Windows image "{0}" in "{1}"' -f $wimFilePath, $winImagePath)
#Expand-WindowsImage -ImagePath $wimFilePath -Index $imageIndex -ApplyPath $winImagePath
# Use Dism in place of the PowerShell equivalent for better progress update
# and for ease of interruption with CTRL+C
& Dism.exe /apply-image /imagefile:${wimFilePath} /index:${imageIndex} /ApplyDir:${winImagePath}
if($LASTEXITCODE) { throw "Dism apply-image failed" }
}
function CreateBCDBootConfig($systemDrive, $windowsDrive, $diskLayout, $image)
{
$bcdbootPath = "${windowsDrive}\windows\system32\bcdboot.exe"
if (!(Test-Path $bcdbootPath))
{
Write-Warning ('"{0}" not found, using online version' -f $bcdbootPath)
$bcdbootPath = "bcdboot.exe"
}
# TODO: add support for UEFI boot
# Note: older versions of bcdboot.exe don't have a /f argument
if ($image.ImageVersion.Major -eq 6 -and $image.ImageVersion.Minor -lt 2)
{
& $bcdbootPath ${windowsDrive}\windows /s ${systemDrive} /v
} else
{
& $bcdbootPath ${windowsDrive}\windows /s ${systemDrive} /v /f $diskLayout
}
if($LASTEXITCODE) { throw "BCDBoot failed" }
if($diskLayout -eq "BIOS")
{
$bcdeditPath = "${windowsDrive}\windows\system32\bcdedit.exe"
if (!(Test-Path $bcdeditPath))
{
Write-Warning ('"{0}" not found, using online version' -f $bcdeditPath)
$bcdeditPath = "bcdedit.exe"
}
& $bcdeditPath /store ${systemDrive}\boot\BCD /set `{bootmgr`} device locate
if ($LASTEXITCODE) { Write-Warning "BCDEdit failed: bootmgr device locate" }
& $bcdeditPath /store ${systemDrive}\boot\BCD /set `{default`} device locate
if ($LASTEXITCODE) { Write-Warning "BCDEdit failed: default device locate" }
& $bcdeditPath /store ${systemDrive}\boot\BCD /set `{default`} osdevice locate
if ($LASTEXITCODE) { Write-Warning "BCDEdit failed: default osdevice locate" }
}
}
function TransformXml($xsltPath, $inXmlPath, $outXmlPath, $xsltArgs)
{
$xslt = New-Object System.Xml.Xsl.XslCompiledTransform($false)
$xsltSettings = New-Object System.Xml.Xsl.XsltSettings($false, $true)
$xslt.Load($xsltPath, $xsltSettings, (New-Object System.Xml.XmlUrlResolver))
$outXmlFile = New-Object System.IO.FileStream($outXmlPath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)
$argList = new-object System.Xml.Xsl.XsltArgumentList
foreach($k in $xsltArgs.Keys)
{
$argList.AddParam($k, "", $xsltArgs[$k])
}
$xslt.Transform($inXmlPath, $argList, $outXmlFile)
$outXmlFile.Close()
}
function GenerateUnattendXml($inUnattendXmlPath, $outUnattendXmlPath, $image, $productKey, $administratorPassword)
{
$xsltArgs = @{}
$xsltArgs["processorArchitecture"] = ([string]$image.ImageArchitecture).ToLower()
$xsltArgs["imageName"] = $image.ImageName
$xsltArgs["versionMajor"] = $image.ImageVersion.Major
$xsltArgs["versionMinor"] = $image.ImageVersion.Minor
$xsltArgs["installationType"] = $image.ImageInstallationType
$xsltArgs["administratorPassword"] = $administratorPassword
if($productKey) {
$xsltArgs["productKey"] = $productKey
}
TransformXml "$scriptPath\Unattend.xslt" $inUnattendXmlPath $outUnattendXmlPath $xsltArgs
}
function DetachVirtualDisk($vhdPath)
{
try
{
$v = [WIMInterop.VirtualDisk]::OpenVirtualDisk($vhdPath)
$v.DetachVirtualDisk()
}
finally
{
if($v) { $v.Close() }
}
}
function GetDismVersion()
{
return new-Object System.Version (gcm dism.exe).FileVersionInfo.ProductVersion
}
function CheckDismVersionForImage($image)
{
$dismVersion = GetDismVersion
if ($image.ImageVersion.CompareTo($dismVersion) -gt 0)
{
Write-Warning "The installed version of DISM is older than the Windows image"
}
}
function ConvertVirtualDisk($vhdPath, $outPath, $format)
{
Write-Output "Converting virtual disk image from $vhdPath to $outPath..."
ExecRetry {
& $scriptPath\bin\qemu-img.exe convert -O $format.ToLower() $vhdPath $outPath
if($LASTEXITCODE) { throw "qemu-img failed to convert the virtual disk" }
}
}
function CopyUnattendResources($resourcesDir, $imageInstallationType)
{
# Workaround to recognize the $resourcesDir drive. This seems a PowerShell bug
$drives = Get-PSDrive
if(!(Test-Path "$resourcesDir")) { $d = mkdir "$resourcesDir" }
copy -Recurse "$localResourcesDir\*" $resourcesDir
if ($imageInstallationType -eq "Server Core")
{
# Skip the wallpaper on server core
del -Force "$resourcesDir\Wallpaper.png"
del -Force "$resourcesDir\GPO.zip"
}
}
function DownloadCloudbaseInit($resourcesDir, $osArch)
{
Write-Output "Downloading Cloudbase-Init..."
if($osArch -eq "AMD64")
{
$CloudbaseInitMsi = "CloudbaseInitSetup_Stable_x64.msi"
}
else
{
$CloudbaseInitMsi = "CloudbaseInitSetup_Stable_x86.msi"
}
$CloudbaseInitMsiPath = "$resourcesDir\CloudbaseInit.msi"
$CloudbaseInitMsiUrl = "https://www.cloudbase.it/downloads/$CloudbaseInitMsi"
ExecRetry {
(New-Object System.Net.WebClient).DownloadFile($CloudbaseInitMsiUrl, $CloudbaseInitMsiPath)
}
}
function GenerateConfigFile($resourcesDir, $installUpdates)
{
$configIniPath = "$resourcesDir\config.ini"
Import-Module "$localResourcesDir\ini.psm1"
Set-IniFileValue -Path $configIniPath -Section "DEFAULT" -Key "InstallUpdates" -Value $installUpdates
}
function AddDriversToImage($winImagePath, $driversPath)
{
Write-Output ('Adding drivers from "{0}" to image "{1}"' -f $driversPath, $winImagePath)
Add-WindowsDriver -Path $winImagePath -Driver $driversPath -ForceUnsigned -Recurse
#& Dism.exe /image:${winImagePath} /Add-Driver /driver:${driversPath} /ForceUnsigned /recurse
#if ($LASTEXITCODE) { throw "Dism failed to add drivers from: $driversPath" }
}
function SetProductKeyInImage($winImagePath, $productKey)
{
Set-WindowsProductKey -Path $winImagePath -ProductKey $productKey
}
function EnableFeaturesInImage($winImagePath, $featureNames)
{
if($featureNames)
{
$featuresCmdStr = "& Dism.exe /image:${winImagePath} /Enable-Feature"
foreach($featureName in $featureNames)
{
$featuresCmdStr += " /FeatureName:$featureName"
}
# Prefer Dism over Enable-WindowsOptionalFeature due to better error reporting
ExecRetry {
Invoke-Expression $featuresCmdStr
if ($LASTEXITCODE) { throw "Dism failed to enable features: $featureNames" }
}
}
}
function CheckEnablePowerShellInImage($winImagePath, $image)
{
# Windows 2008 R2 Server Core dows not enable powershell by default
$v62 = new-Object System.Version 6, 2, 0, 0
if($image.ImageVersion.CompareTo($v62) -lt 0 -and $image.ImageInstallationType -eq "Server Core")
{
Write-Output "Enabling PowerShell in the Windows image"
$psFeatures = @("NetFx2-ServerCore", "MicrosoftWindowsPowerShell", `
"NetFx2-ServerCore-WOW64", "MicrosoftWindowsPowerShell-WOW64")
EnableFeaturesInImage $winImagePath $psFeatures
}
}
function Is-IsoFile {
param(
[parameter(Mandatory=$true)]
[string]$FilePath
)
return ([System.IO.Path]::GetExtension($FilePath) -eq ".iso")
}
function Add-VirtIODrivers($vhdDriveLetter, $image, $driversBasePath)
{
# For VirtIO ISO with drivers version lower than 1.8.x
if ($image.ImageVersion.Major -eq 6 -and $image.ImageVersion.Minor -eq 0) {
$virtioVer = "VISTA"
} elseif ($image.ImageVersion.Major -eq 6 -and $image.ImageVersion.Minor -eq 1) {
$virtioVer = "WIN7"
} elseif (($image.ImageVersion.Major -eq 6 -and $image.ImageVersion.Minor -ge 2) `
-or $image.ImageVersion.Major -gt 6) {
$virtioVer = "WIN8"
} else {
throw "Unsupported Windows version for VirtIO drivers: {0}" `
-f $image.ImageVersion
}
$virtioDir = "{0}\{1}\{2}" -f $driversBasePath, $virtioVer, $image.ImageArchitecture
if (Test-Path $virtioDir) {
AddDriversToImage $vhdDriveLetter $virtioDir
return
}
# For VirtIO ISO with drivers version higher than 1.8.x
if ($image.ImageVersion.Major -eq 6 -and $image.ImageVersion.Minor -eq 0) {
$virtioVer = "2k8"
} elseif ($image.ImageVersion.Major -eq 6 -and $image.ImageVersion.Minor -eq 1) {
if ($image.ImageInstallationType -eq "Server") {
$virtioVer = "2k8r2"
} else {
$virtioVer = "w7"
}
} elseif ($image.ImageVersion.Major -eq 6 -and $image.ImageVersion.Minor -eq 2) {
if ($image.ImageInstallationType -eq "Server") {
$virtioVer = "2k12"
} else {
$virtioVer = "w8"
}
} elseif (($image.ImageVersion.Major -eq 6 -and $image.ImageVersion.Minor -ge 3) `
-or $image.ImageVersion.Major -gt 6) {
if ($image.ImageInstallationType -eq "Server") {
$virtioVer = "2k12R2"
} else {
$virtioVer = "w8.1"
}
} else {
throw "Unsupported Windows version for VirtIO drivers: {0}" `
-f $image.ImageVersion
}
$drivers = @("Balloon", "NetKVM", "viorng", "vioscsi", "vioserial", "viostor")
foreach ($driver in $drivers) {
$virtioDir = "{0}\{1}\{2}\{3}" -f $driversBasePath, $driver, $virtioVer, $image.ImageArchitecture
if (Test-Path $virtioDir) {
AddDriversToImage $vhdDriveLetter $virtioDir
}
}
}
function Add-VirtIODriversFromISO($vhdDriveLetter, $image, $isoPath) {
$v = [WIMInterop.VirtualDisk]::OpenVirtualDisk($isoPath)
try {
if (Is-IsoFile $isoPath) {
$v.AttachVirtualDisk()
$devicePath = $v.GetVirtualDiskPhysicalPath()
$driversBasePath = ((Get-DiskImage -DevicePath $devicePath `
| Get-Volume).DriveLetter) + ":"
Write-Host "Adding drivers from $driversBasePath"
# We call Get-PSDrive to refresh the list of active drives.
# Otherwise, "Test-Path $driversBasePath" will return $False
# http://www.vistax64.com/powershell/2653-powershell-does-not-update-subst-mapped-drives.html
Get-PSDrive | Out-Null
Add-VirtIODrivers $vhdDriveLetter $image $driversBasePath
} else {
throw "The $isoPath is not a valid iso path."
}
} catch{
Write-Host $_
} finally {
if ($v) {
$v.DetachVirtualDisk()
$v.Close()
}
}
}
function SetDotNetCWD()
{
# Make sure the PowerShell and .Net CWD match
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
}
function GetPathWithoutExtension($path)
{
return Join-Path ([System.IO.Path]::GetDirectoryName($path)) `
([System.IO.Path]::GetFileNameWithoutExtension($path))
}
function New-WindowsCloudImage()
{
[CmdletBinding()]
param
(
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]$WimFilePath = "D:\Sources\install.wim",
[parameter(Mandatory=$true)]
[string]$ImageName,
[parameter(Mandatory=$true)]
[string]$VirtualDiskPath,
[parameter(Mandatory=$true)]
[Uint64]$SizeBytes,
[parameter(Mandatory=$false)]
[string]$ProductKey,
[parameter(Mandatory=$false)]
[ValidateSet("VHD", "VHDX", "QCow2", "VMDK", "RAW", ignorecase=$false)]
[string]$VirtualDiskFormat = "VHDX",
[ValidateSet("BIOS", "UEFI", ignorecase=$false)]
[string]$DiskLayout = "BIOS",
[parameter(Mandatory=$false)]
[string]$VirtIOISOPath,
[parameter(Mandatory=$false)]
[switch]$InstallUpdates,
[parameter(Mandatory=$false)]
[string]$AdministratorPassword = "Pa`$`$w0rd",
[parameter(Mandatory=$false)]
[string]$UnattendXmlPath = "$scriptPath\UnattendTemplate.xml",
[parameter(Mandatory=$false)]
[string]$VirtIOBasePath
)
PROCESS
{
SetDotNetCWD
CheckIsAdmin
$image = Get-WimFileImagesInfo -WimFilePath $wimFilePath | where {$_.ImageName -eq $ImageName }
if(!$image) { throw 'Image "$ImageName" not found in WIM file "$WimFilePath"'}
CheckDismVersionForImage $image
if (Test-Path $VirtualDiskPath) { Remove-Item -Force $VirtualDiskPath }
if ($VirtualDiskFormat -in @("VHD", "VHDX"))
{
$VHDPath = $VirtualDiskPath
}
else
{
$VHDPath = "{0}.vhd" -f (GetPathWithoutExtension $VirtualDiskPath)
if (Test-Path $VHDPath) { Remove-Item -Force $VHDPath }
}
try
{
$drives = CreateImageVirtualDisk $VHDPath $SizeBytes $DiskLayout
$winImagePath = "$($drives[1])\"
$resourcesDir = "${winImagePath}UnattendResources"
$unattedXmlPath = "${winImagePath}Unattend.xml"
GenerateUnattendXml $UnattendXmlPath $unattedXmlPath $image $ProductKey $AdministratorPassword
CopyUnattendResources $resourcesDir $image.ImageInstallationType
CreateBCDBootConfig $drives[0] $drives[1] $DiskLayout $image
DownloadCloudbaseInit $resourcesDir ([string]$image.ImageArchitecture)
ApplyImage $winImagePath $wimFilePath $image.ImageIndex
CreateBCDBootConfig $drives[0] $drives[1] $DiskLayout
CheckEnablePowerShellInImage $winImagePath $image
# Product key is applied by the unattend.xml
# Evaluate if it's the case to set the product key here as well
# which in case requires Dism /Set-Edition
#if($ProductKey)
#{
# SetProductKeyInImage $winImagePath $ProductKey
#}
if($VirtIOISOPath)
{
Add-VirtIODriversFromISO $winImagePath $image $VirtIOISOPath
}
if($VirtIOBasePath)
{
Add-VirtIODrivers $winImagePath $image $VirtIOBasePath
}
}
finally
{
if (Test-Path $VHDPath)
{
DetachVirtualDisk $VHDPath
}
}
if ($VHDPath -ne $VirtualDiskPath)
{
ConvertVirtualDisk $VHDPath $VirtualDiskPath $VirtualDiskFormat
del -Force $VHDPath
}
}
}
Export-ModuleMember New-WindowsCloudImage, Get-WimFileImagesInfo