forked from cloudbase/windows-imaging-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WinImageBuilder.psm1
380 lines (330 loc) · 12.3 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
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 2
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$localResourcesDir = "$scriptPath\UnattendResources"
. "$scriptPath\Interop.ps1"
Import-Module dism
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)
{
$v = [WIMInterop.VirtualDisk]::CreateVirtualDisk($vhdPath, $size)
try
{
$v.AttachVirtualDisk()
$path = $v.GetVirtualDiskPhysicalPath()
$m = $path -match "\\\\.\\PHYSICALDRIVE(?<num>\d+)"
$diskNum = $matches["num"]
$volumeLabel = "OS"
Initialize-Disk -Number $diskNum -PartitionStyle MBR
$part = New-Partition -DiskNumber $diskNum -UseMaximumSize -AssignDriveLetter -IsActive
$driveLetter = $part.DriveLetter
$format = Format-Volume -DriveLetter $driveLetter -FileSystem NTFS -NewFileSystemLabel $volumeLabel -Force -Confirm:$false
return $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($driveLetter)
{
$bcdbootPath = "${driveLetter}:\windows\system32\bcdboot.exe"
if (!(Test-Path $bcdbootPath))
{
Write-Warning ('"{0}" not found, using online version' -f $bcdbootPath)
$bcdbootPath = "bcdboot.exe"
}
& $bcdbootPath ${driveLetter}:\windows /s ${driveLetter}: /v
if($LASTEXITCODE) { throw "BCDBoot failed" }
#& ${driveLetter}:\Windows\System32\bcdedit.exe /store ${driveLetter}:\boot\BCD
#if($LASTEXITCODE) { throw "BCDEdit failed" }
}
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
{
$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..."
& $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_Beta_x64.msi"
}
else
{
$CloudbaseInitMsi = "CloudbaseInitSetup_Beta_x86.msi"
}
$CloudbaseInitMsiPath = "$resourcesDir\CloudbaseInit.msi"
$CloudbaseInitMsiUrl = "https://www.cloudbase.it/downloads/$CloudbaseInitMsi"
(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
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 AddVirtIODriversFromISO($vhdDriveLetter, $image, $isoPath)
{
$v = [WIMInterop.VirtualDisk]::OpenVirtualDisk($isoPath)
try
{
$v.AttachVirtualDisk()
$devicePath = $v.GetVirtualDiskPhysicalPath()
$isoDriveLetter = (Get-DiskImage -DevicePath $devicePath | Get-Volume).DriveLetter
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 $isoDriveLetter, $virtioVer, $image.ImageArchitecture
AddDriversToImage $vhdDriveLetter $virtioDir
}
finally
{
$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", "QCow2", "VMDK", "RAW", ignorecase=$false)]
[string]$VirtualDiskFormat = "VHD",
[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"
)
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
{
$driveLetter = CreateImageVirtualDisk $VHDPath $SizeBytes
$winImagePath = "${driveLetter}:\"
$resourcesDir = "${winImagePath}UnattendResources"
$unattedXmlPath = "${winImagePath}Unattend.xml"
GenerateUnattendXml $UnattendXmlPath $unattedXmlPath $image $ProductKey $AdministratorPassword
CopyUnattendResources $resourcesDir $image.ImageInstallationType
GenerateConfigFile $resourcesDir $installUpdates
DownloadCloudbaseInit $resourcesDir ([string]$image.ImageArchitecture)
ApplyImage $winImagePath $wimFilePath $image.ImageIndex
CreateBCDBootConfig $driveLetter
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)
{
AddVirtIODriversFromISO $winImagePath $image $VirtIOISOPath
}
}
finally
{
if (Test-Path $VHDPath)
{
DetachVirtualDisk $VHDPath
}
}
if ($VHDPath -ne $VirtualDiskPath)
{
ConvertVirtualDisk $VHDPath $VirtualDiskPath $VirtualDiskFormat
del -Force $VHDPath
}
}
}
Export-ModuleMember New-WindowsCloudImage, Get-WimFileImagesInfo