| 1 | #requires -Version 5.1 |
| 2 | <# |
| 3 | .SYNOPSIS |
| 4 | Prepare a one-use answer DVD for the empty offline VM created by new-windows-test-vm.ps1. |
| 5 | .DESCRIPTION |
| 6 | Targets an x64 en-US Windows 11 Enterprise Evaluation image. Windows Setup inside |
| 7 | the VM partitions its empty VHDX. The Microsoft OOBE, account and activation |
| 8 | requirements are retained. Pass -AcceptEvaluationTerms only after reviewing the |
| 9 | terms for this evaluation. Otherwise Setup asks inside the VM. -Start boots |
| 10 | the VM now. The answer file has no credentials. |
| 11 | .LINK |
| 12 | https://learn.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-setup-userdata-accepteula |
| 13 | .LINK |
| 14 | https://www.microsoft.com/en-us/evalcenter/evaluate-windows-11-enterprise |
| 15 | #> |
| 16 | [CmdletBinding()] |
| 17 | param( |
| 18 | [Parameter(Mandatory)][guid]$VMId, |
| 19 | [Parameter(Mandatory)][string]$InstanceDirectory, |
| 20 | [Parameter(Mandatory)][ValidatePattern('^[a-fA-F0-9]{64}$')][string]$ExpectedIsoSha256, |
| 21 | [string]$PowerShellZip, |
| 22 | [switch]$AcceptEvaluationTerms, |
| 23 | [switch]$Start |
| 24 | ) |
| 25 | $ErrorActionPreference = 'Stop' |
| 26 | . (Join-Path $PSScriptRoot 'windows-guest-media.ps1') |
| 27 | |
| 28 | function New-EvaluationAnswer([string]$Template, [int]$ImageIndex, [long]$DiskBytes, [bool]$TermsAccepted) { |
| 29 | if ($ImageIndex -lt 1 -or $DiskBytes -lt 64GB) { throw 'Invalid evaluation image index or disk capacity.' } |
| 30 | # Preserve 1.5 GiB for WinRE, plus GPT alignment, the ESP and MSR. |
| 31 | $osMiB = [long][Math]::Floor($DiskBytes / 1MB) - 1536 - 2 - 260 - 16 |
| 32 | return $Template.Replace('OS_SIZE_MIB', "$osMiB").Replace('EVAL_IMAGE_INDEX', "$ImageIndex").Replace('ACCEPT_EULA', $TermsAccepted.ToString().ToLowerInvariant()) |
| 33 | } |
| 34 | |
| 35 | function Get-EvaluationImage([string]$Path) { |
| 36 | $alreadyMounted = (Get-DiskImage -ImagePath $Path).Attached |
| 37 | if (!$alreadyMounted) { $null = Mount-DiskImage -ImagePath $Path -Access ReadOnly -StorageType ISO } |
| 38 | try { |
| 39 | $volume = @(Get-DiskImage -ImagePath $Path | Get-Volume) |
| 40 | if ($volume.Count -ne 1 -or !$volume[0].DriveLetter) { throw 'Cannot inspect the setup ISO.' } |
| 41 | $sources = '{0}:\sources' -f $volume[0].DriveLetter |
| 42 | $images = @(@('install.wim','install.esd') | ForEach-Object { Join-Path $sources $_ } | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf }) |
| 43 | if ($images.Count -ne 1) { throw 'Expected one official Windows installation image.' } |
| 44 | $matchingImages = @(foreach ($entry in (Get-WindowsImage -ImagePath $images[0])) { |
| 45 | $detail = Get-WindowsImage -ImagePath $images[0] -Index $entry.ImageIndex |
| 46 | if ($detail.EditionId -eq 'EnterpriseEval' -and [string]$detail.Architecture -in @('9','amd64','x64') -and $detail.Languages -contains 'en-US') { |
| 47 | $detail |
| 48 | } |
| 49 | }) |
| 50 | if ($matchingImages.Count -ne 1) { throw 'The ISO must contain exactly one x64 en-US EnterpriseEval image.' } |
| 51 | return $matchingImages[0] |
| 52 | } finally { |
| 53 | if (!$alreadyMounted) { $null = Dismount-DiskImage -ImagePath $Path } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | if ([Environment]::OSVersion.Platform -ne 'Win32NT' -or ![Environment]::Is64BitProcess) { |
| 58 | throw 'Run in 64-bit Windows PowerShell on the Hyper-V host.' |
| 59 | } |
| 60 | $root = Get-Item -LiteralPath $InstanceDirectory |
| 61 | $vm = Get-VM -Id $VMId |
| 62 | $firmware = Get-VMFirmware -VM $vm |
| 63 | $configPath = [IO.Path]::GetFullPath($vm.ConfigurationLocation).TrimEnd('\') |
| 64 | if ($root -isnot [IO.DirectoryInfo] -or ($root.Attributes -band [IO.FileAttributes]::ReparsePoint) -or |
| 65 | ($configPath -ne $root.FullName -and !$configPath.StartsWith($root.FullName + '\', [StringComparison]::OrdinalIgnoreCase)) -or |
| 66 | $vm.State -ne 'Off' -or $vm.Generation -ne 2 -or @(Get-VMNetworkAdapter -VM $vm).Count -or |
| 67 | @(Get-VMSnapshot -VM $vm).Count -or !(Get-VMSecurity -VM $vm).TpmEnabled -or |
| 68 | $firmware.SecureBoot -ne 'On' -or $firmware.SecureBootTemplate -ne 'MicrosoftWindows') { |
| 69 | throw 'Expected a stopped, offline, checkpoint-free generation 2 test VM with Secure Boot and vTPM.' |
| 70 | } |
| 71 | $drives = @(Get-VMHardDiskDrive -VM $vm) |
| 72 | $answerDir = Join-Path $root.FullName 'evaluation-setup' |
| 73 | $mode = if ($AcceptEvaluationTerms) { 'accepted' } else { 'native' } |
| 74 | $mediaDir = Join-Path $answerDir ($mode + '-pwsh7') |
| 75 | $answerISO = Join-Path $mediaDir 'answer.iso' |
| 76 | $genericAnswer = Join-Path $root.FullName 'windows-guest-tools.iso' |
| 77 | $knownAnswers = @('accepted','native','accepted-pwsh7','native-pwsh7') | ForEach-Object { Join-Path (Join-Path $answerDir $_) 'answer.iso' } |
| 78 | $knownAnswers = @($knownAnswers) + @($genericAnswer) |
| 79 | $allDVDs = @(Get-VMDvdDrive -VM $vm) |
| 80 | $dvds = @($allDVDs | Where-Object { $_.Path -notin $knownAnswers }) |
| 81 | $priorAnswers = @($allDVDs | Where-Object { $_.Path -in $knownAnswers }) |
| 82 | $expectedDisk = Join-Path $root.FullName 'system.vhdx' |
| 83 | if ($drives.Count -ne 1 -or $drives[0].Path -ne $expectedDisk -or $dvds.Count -ne 1 -or !$dvds[0].Path -or $priorAnswers.Count -gt 1) { |
| 84 | throw 'Expected the single system.vhdx and original installation DVD created for this VM.' |
| 85 | } |
| 86 | if (@(Get-VM | Get-VMHardDiskDrive | Where-Object Path -eq $expectedDisk).Count -ne 1) { |
| 87 | throw 'The empty test disk must belong exclusively to the selected VM.' |
| 88 | } |
| 89 | $diskFile = Get-Item -LiteralPath $expectedDisk |
| 90 | $vhd = Get-VHD -Path $diskFile.FullName |
| 91 | if ($diskFile.Attributes -band [IO.FileAttributes]::ReparsePoint -or $vhd.VhdType -ne 'Dynamic' -or $vhd.ParentPath -or $vhd.Attached) { |
| 92 | throw 'Expected an unattached standalone dynamic VHDX in the test instance directory.' |
| 93 | } |
| 94 | $iso = Get-Item -LiteralPath $dvds[0].Path |
| 95 | if ($iso.Extension -ne '.iso' -or (Get-FileHash -LiteralPath $iso.FullName -Algorithm SHA256).Hash -ne $ExpectedIsoSha256) { |
| 96 | throw 'The mounted setup DVD does not match the expected Microsoft ISO digest.' |
| 97 | } |
| 98 | $edition = Get-EvaluationImage $iso.FullName |
| 99 | |
| 100 | # Publish a complete media directory before touching any boot device. A retry |
| 101 | # can reuse that media after a DVD attach or firmware error, even on a new shell. |
| 102 | $null = [IO.Directory]::CreateDirectory($answerDir) |
| 103 | if ((Get-Item -LiteralPath $answerDir).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Unexpected redirected answer directory.' } |
| 104 | $lock = [IO.File]::Open((Join-Path $answerDir 'setup.lock'), 'OpenOrCreate', 'ReadWrite', 'None') |
| 105 | try { |
| 106 | if ((Get-VM -Id $VMId).State -ne 'Off') { throw 'The test VM started during preparation.' } |
| 107 | $null = Mount-VHD -Path $diskFile.FullName -ReadOnly -NoDriveLetter |
| 108 | try { |
| 109 | $virtualDisk = Get-VHD -Path $diskFile.FullName | Get-Disk |
| 110 | if (!$virtualDisk.IsReadOnly -or $virtualDisk.PartitionStyle -ne 'RAW') { throw 'Refusing to install on a disk that is not empty and RAW.' } |
| 111 | } finally { Dismount-VHD -Path $diskFile.FullName } |
| 112 | if (!(Test-Path -LiteralPath $mediaDir)) { |
| 113 | $stage = Join-Path $answerDir ([guid]::NewGuid().ToString('N')) |
| 114 | $stageISO = Join-Path $stage 'answer.iso' |
| 115 | $stageReceipt = Join-Path $stage 'receipt.json' |
| 116 | $null = [IO.Directory]::CreateDirectory($stage) |
| 117 | try { |
| 118 | $answer = New-EvaluationAnswer ([IO.File]::ReadAllText((Join-Path $PSScriptRoot 'windows-evaluation-autounattend.xml'))) $edition.ImageIndex $vhd.Size $AcceptEvaluationTerms.IsPresent |
| 119 | New-WindowsGuestAnswerISO $stageISO ([xml]$answer) $PowerShellZip $genericAnswer |
| 120 | Grant-VMAnswerReadAccess $stageISO $VMId |
| 121 | $metadata = [ordered]@{ |
| 122 | VMId = $vm.Id; InstanceDirectory = $root.FullName; Disk = $diskFile.FullName |
| 123 | Edition = $edition.EditionId; ImageIndex = $edition.ImageIndex |
| 124 | WindowsIsoSHA256 = $ExpectedIsoSha256; AnswerISO = $answerISO |
| 125 | AnswerSHA256 = (Get-FileHash -LiteralPath $stageISO -Algorithm SHA256).Hash |
| 126 | LicenseUI = $mode; RequiresMicrosoftOOBE = $true |
| 127 | PowerShellVersion = $GuestPowerShellVersion; PowerShellSHA256 = $GuestPowerShellSHA256 |
| 128 | } |
| 129 | if ($AcceptEvaluationTerms) { $metadata['EvaluationTermsAcceptedUtc'] = [DateTime]::UtcNow.ToString('o') } |
| 130 | [IO.File]::WriteAllText($stageReceipt, ($metadata | ConvertTo-Json)) |
| 131 | [IO.Directory]::Move($stage, $mediaDir) |
| 132 | } finally { |
| 133 | # Only remove files created in this attempt's unique staging folder. |
| 134 | if ([IO.Directory]::Exists($stage)) { |
| 135 | foreach ($f in @($stageISO, $stageReceipt)) { [IO.File]::Delete($f) } |
| 136 | [IO.Directory]::Delete($stage) |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | $mediaReceipt = Join-Path $mediaDir 'receipt.json' |
| 141 | $receipt = Get-Content -LiteralPath $mediaReceipt -Raw | ConvertFrom-Json |
| 142 | if ([guid]$receipt.VMId -ne $VMId -or $receipt.Disk -ne $diskFile.FullName -or $receipt.AnswerISO -ne $answerISO -or |
| 143 | $receipt.WindowsIsoSHA256 -ne $ExpectedIsoSha256 -or $receipt.LicenseUI -ne $mode -or |
| 144 | $receipt.PowerShellSHA256 -ne $GuestPowerShellSHA256 -or |
| 145 | $receipt.AnswerSHA256 -ne (Get-FileHash -LiteralPath $answerISO -Algorithm SHA256).Hash) { |
| 146 | throw 'Existing answer media does not match this VM, installer or license selection.' |
| 147 | } |
| 148 | # Refresh the DVD inventory under the lock. Only the two answer files |
| 149 | # belonging to this private instance are eligible for replacement. |
| 150 | $priorAnswers = @(Get-VMDvdDrive -VM $vm | Where-Object { $_.Path -in $knownAnswers }) |
| 151 | if ($priorAnswers.Count -gt 1) { throw 'More than one answer DVD is attached.' } |
| 152 | if ($priorAnswers.Count -eq 0) { $dvd = Add-VMDvdDrive -VM $vm -Path $answerISO -Passthru } |
| 153 | elseif ($priorAnswers[0].Path -eq $answerISO) { $dvd = $priorAnswers[0] } |
| 154 | else { $dvd = Set-VMDvdDrive -VMDvdDrive $priorAnswers[0] -Path $answerISO -Passthru } |
| 155 | # The installed disk wins after the first reboot. The original Microsoft DVD |
| 156 | # boots when that disk is blank. The answer DVD contains only data. |
| 157 | Set-VMFirmware -VM $vm -BootOrder @($drives[0], $dvds[0], $dvd) |
| 158 | $receiptPath = Join-Path $answerDir 'receipt.json' |
| 159 | $tempReceipt = Join-Path $answerDir ([guid]::NewGuid().ToString('N') + '.tmp') |
| 160 | try { |
| 161 | [IO.File]::Copy($mediaReceipt, $tempReceipt) |
| 162 | if ([IO.File]::Exists($receiptPath)) { |
| 163 | [IO.File]::Replace($tempReceipt, $receiptPath, [Management.Automation.Language.NullString]::Value) |
| 164 | } else { [IO.File]::Move($tempReceipt, $receiptPath) } |
| 165 | } finally { [IO.File]::Delete($tempReceipt) } |
| 166 | if ($Start) { |
| 167 | Start-VM -VM $vm | Out-Null |
| 168 | # The original installer DVD can request one boot key. N cannot confirm |
| 169 | # a license prompt. Send it only during the first boot of this blank VM. |
| 170 | $namespace = 'root/virtualization/v2' |
| 171 | $system = Get-CimInstance -Namespace $namespace -ClassName Msvm_ComputerSystem -Filter "Name='$VMId'" |
| 172 | $keyboard = @(Get-CimAssociatedInstance -InputObject $system -ResultClassName Msvm_Keyboard) |
| 173 | if ($keyboard.Count -eq 1) { |
| 174 | for ($i = 0; $i -lt 5; $i++) { |
| 175 | Start-Sleep -Seconds 1 |
| 176 | $key = Invoke-CimMethod -InputObject $keyboard[0] -MethodName TypeKey -Arguments @{ keyCode = [uint32]0x4E } |
| 177 | if ($key.ReturnValue -ne 0) { Write-Warning 'Check the DVD boot prompt in VMConnect.'; break } |
| 178 | } |
| 179 | } else { Write-Warning 'Check the DVD boot prompt in VMConnect.' } |
| 180 | } |
| 181 | } finally { $lock.Dispose() } |
| 182 | $receipt |