| 1 | #requires -Version 5.1 |
| 2 | <# |
| 3 | .SYNOPSIS |
| 4 | Create an offline Windows 11 x64 test VM on a local Hyper-V host. |
| 5 | .DESCRIPTION |
| 6 | Supply a Windows ISO that you are licensed to use and a new directory under |
| 7 | an existing local folder. -ExpectedIsoSha256 can check the digest published |
| 8 | by your media provider. The new VM has no network adapter. Its configuration, |
| 9 | disk and guest TPM state stay together after shutdown. Use the returned VMId |
| 10 | as -ExpectedVMId for claude-desktop-windows.ps1. -Start boots only this VM. |
| 11 | Windows Setup installs PowerShell 7 for all guest users. Supply -PowerShellZip |
| 12 | to use an existing copy of the pinned Microsoft archive on an offline host. |
| 13 | Manual ISO setup prompts for the guest's initial local administrator. Supply |
| 14 | -GuestAdministrator to provide it directly. Windows Setup uses the protected |
| 15 | answer DVD to create that account without a network connection. |
| 16 | #> |
| 17 | [CmdletBinding(SupportsShouldProcess)] |
| 18 | param( |
| 19 | [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Name, |
| 20 | [Parameter(Mandatory)][string]$IsoPath, |
| 21 | [Parameter(Mandatory)][string]$InstanceDirectory, |
| 22 | [ValidatePattern('^[0-9A-Fa-f]{64}$')][string]$ExpectedIsoSha256, |
| 23 | [string]$PowerShellZip, |
| 24 | [string]$ImageEdition, |
| 25 | [string]$ImageLanguage, |
| 26 | [string]$ImageBuild, |
| 27 | [pscredential]$GuestAdministrator, |
| 28 | [ValidateRange(2, 2048)][int]$CpuCount = 2, |
| 29 | [ValidateRange(4, 65536)][int]$MemoryGiB = 4, |
| 30 | [ValidateRange(64, 65536)][int]$DiskGiB = 64, |
| 31 | [switch]$Start |
| 32 | ) |
| 33 | $ErrorActionPreference = 'Stop' |
| 34 | . (Join-Path $PSScriptRoot 'windows-guest-media.ps1') |
| 35 | . (Join-Path $PSScriptRoot 'windows-host-image.ps1') |
| 36 | $fromHost = ![string]::IsNullOrEmpty($ImageEdition) |
| 37 | |
| 38 | function Set-TestVMResources($VM, [int]$Processors, [long]$MemoryBytes) { |
| 39 | # New-VM can inherit Dynamic Memory with a 1 TiB maximum on a client host. |
| 40 | Set-VM -VM $VM -ProcessorCount $Processors -StaticMemory -MemoryStartupBytes $MemoryBytes -AutomaticStartAction Nothing -AutomaticCheckpointsEnabled $false |
| 41 | $memory = Get-VMMemory -VM $VM |
| 42 | if ($memory.DynamicMemoryEnabled -or $memory.Startup -ne $MemoryBytes) { |
| 43 | throw 'The VM memory allocation does not match the requested fixed budget.' |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | if ([Environment]::OSVersion.Platform -ne 'Win32NT' -or ![Environment]::Is64BitProcess) { |
| 48 | throw 'Run this script in 64-bit Windows PowerShell on the Hyper-V host.' |
| 49 | } |
| 50 | if ($Name.Trim() -ne $Name -or $Name -match '[\x00-\x1f*?\[\]\\/:|"<>]') { throw 'Invalid VM name.' } |
| 51 | $system = Get-CimInstance Win32_ComputerSystem |
| 52 | $os = Get-CimInstance Win32_OperatingSystem |
| 53 | $nativeCpu = @(Get-CimInstance Win32_Processor | Where-Object Architecture -ne 9) |
| 54 | if ($nativeCpu.Count -gt 0 -or $os.ProductType -ne 1 -or [int]$os.BuildNumber -lt 22000) { |
| 55 | throw 'This prototype requires a native x64 Windows 11 client host.' |
| 56 | } |
| 57 | if (!$system.HypervisorPresent -or (Get-Service vmms).Status -ne 'Running' -or !(Get-VMHost)) { |
| 58 | throw 'Hyper-V must be running and accessible to the current user.' |
| 59 | } |
| 60 | if ($CpuCount -gt $system.NumberOfLogicalProcessors -or ($MemoryGiB * 1GB) -gt ($os.FreePhysicalMemory * 1KB)) { |
| 61 | throw 'The requested CPU count or startup memory exceeds the available host resources.' |
| 62 | } |
| 63 | if (@(Get-VM | Where-Object Name -eq $Name).Count) { throw "A VM named '$Name' already exists." } |
| 64 | |
| 65 | $iso = Get-Item -LiteralPath $IsoPath |
| 66 | if ($iso -isnot [IO.FileInfo] -or ($iso.Extension -ne '.iso' -and !($fromHost -and $iso.Extension -eq '.esd')) -or !$iso.Length -or |
| 67 | $iso.FullName.StartsWith('\\') -or [IO.DriveInfo]::new($iso.Directory.Root.FullName).DriveType -eq 'Network') { |
| 68 | throw 'Supply a local Windows 11 x64 ISO.' |
| 69 | } |
| 70 | if ($ExpectedIsoSha256 -and (Get-FileHash -LiteralPath $iso.FullName -Algorithm SHA256).Hash -ne $ExpectedIsoSha256) { |
| 71 | throw 'The installation ISO does not match the expected SHA-256.' |
| 72 | } |
| 73 | $directory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($InstanceDirectory) |
| 74 | $parent = Get-Item -LiteralPath ([IO.Path]::GetDirectoryName($directory)) |
| 75 | if ($parent -isnot [IO.DirectoryInfo] -or $parent.FullName.StartsWith('\\') -or |
| 76 | [IO.DriveInfo]::new($parent.Root.FullName).DriveType -ne 'Fixed') { |
| 77 | throw 'Choose a new VM directory on a local fixed disk.' |
| 78 | } |
| 79 | if (Test-Path -LiteralPath $directory) { throw "The instance directory already exists: $directory" } |
| 80 | $requiredFree = if ($fromHost) { 32GB } else { 64GB } |
| 81 | if ([IO.DriveInfo]::new($parent.Root.FullName).AvailableFreeSpace -lt $requiredFree) { |
| 82 | throw "Windows creation needs $($requiredFree / 1GB) GiB free on the destination volume. Its virtual disk grows with use." |
| 83 | } |
| 84 | if (!$PSCmdlet.ShouldProcess($directory, "Create offline Hyper-V VM '$Name' (start: $([bool]$Start))")) { return } |
| 85 | |
| 86 | if ($fromHost) { |
| 87 | $answer = New-CageCloneAnswer $GuestAdministrator $ImageLanguage |
| 88 | } else { |
| 89 | if (!$GuestAdministrator) { |
| 90 | $GuestAdministrator = Get-Credential -UserName 'CageAdmin' -Message '设置虚拟 Windows 的初始本地管理员和密码。安装后用此账户登录客机,并在 Cage 继续安装时再次输入。' |
| 91 | } |
| 92 | $answer = New-CageISOAnswer $GuestAdministrator |
| 93 | } |
| 94 | |
| 95 | # Create with a protected ACL, then claim the requested name using a same-volume |
| 96 | # rename that fails atomically if another creation has already won. |
| 97 | $acl = [Security.AccessControl.DirectorySecurity]::new() |
| 98 | $acl.SetAccessRuleProtection($true, $false) |
| 99 | $owner = [Security.Principal.WindowsIdentity]::GetCurrent().User |
| 100 | $acl.SetOwner($owner) |
| 101 | foreach ($sid in @($owner, [Security.Principal.SecurityIdentifier]::new('S-1-5-18'), |
| 102 | [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))) { |
| 103 | $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( |
| 104 | $sid, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow')) |
| 105 | } |
| 106 | $staging = Join-Path $parent.FullName ([Guid]::NewGuid().ToString('N')) |
| 107 | $staged = $false |
| 108 | $claimed = $false |
| 109 | $vm = $null |
| 110 | $diskPath = Join-Path $directory 'system.vhdx' |
| 111 | $toolsISO = Join-Path $directory 'windows-guest-tools.iso' |
| 112 | $ownsToolsISO = $false |
| 113 | try { |
| 114 | if ($PSVersionTable.PSEdition -eq 'Desktop') { |
| 115 | [void][IO.Directory]::CreateDirectory($staging, $acl) |
| 116 | } else { |
| 117 | [IO.FileSystemAclExtensions]::Create([IO.DirectoryInfo]::new($staging), $acl) |
| 118 | } |
| 119 | $staged = $true |
| 120 | [IO.Directory]::Move($staging, $directory) |
| 121 | $staged = $false |
| 122 | $claimed = $true |
| 123 | # The protected second DVD supplies the chosen local account and tools. |
| 124 | # Windows Setup still asks for edition, disk, license and regional settings. |
| 125 | New-WindowsGuestAnswerISO $toolsISO $answer $PowerShellZip |
| 126 | $ownsToolsISO = $true |
| 127 | $vm = New-VM -Name $Name -Generation 2 -MemoryStartupBytes ($MemoryGiB * 1GB) -NoVHD -Path $directory |
| 128 | Set-TestVMResources $vm $CpuCount ($MemoryGiB * 1GB) |
| 129 | Get-VMNetworkAdapter -VM $vm | Remove-VMNetworkAdapter -Confirm:$false |
| 130 | $null = New-VHD -Path $diskPath -SizeBytes ($DiskGiB * 1GB) -Dynamic |
| 131 | if ($fromHost) { Install-CageWindowsImage $iso.FullName $diskPath $ImageEdition $ImageLanguage $answer $ImageBuild } |
| 132 | Add-VMHardDiskDrive -VM $vm -Path $diskPath |
| 133 | $bootDevice = $vm | Get-VMHardDiskDrive |
| 134 | if (!$fromHost) { $bootDevice = Add-VMDvdDrive -VM $vm -Path $iso.FullName -Passthru } |
| 135 | Grant-VMAnswerReadAccess $toolsISO $vm.Id |
| 136 | Add-VMDvdDrive -VM $vm -Path $toolsISO |
| 137 | Set-VMFirmware -VM $vm -EnableSecureBoot On -SecureBootTemplate MicrosoftWindows -FirstBootDevice $bootDevice |
| 138 | Set-VMKeyProtector -VM $vm -NewLocalKeyProtector |
| 139 | Enable-VMTPM -VM $vm |
| 140 | $vm = Get-VM -Id $vm.Id |
| 141 | if (@(Get-VM -Name $Name).Count -ne 1) { throw "Another VM acquired the same name '$Name'." } |
| 142 | if ($vm.AutomaticStartAction -ne 'Nothing' -or @(Get-VMNetworkAdapter -VM $vm).Count -or |
| 143 | (Get-VMFirmware -VM $vm).SecureBoot -ne 'On' -or !(Get-VMSecurity -VM $vm).TpmEnabled) { |
| 144 | throw 'Offline, secure boot or TPM configuration did not pass the post-creation checks.' |
| 145 | } |
| 146 | } catch { |
| 147 | $creationError = $_ |
| 148 | if ($claimed) { |
| 149 | # New-VM can fail after registering. Match the new private configuration |
| 150 | # directory as well as the name before removing any partial registration. |
| 151 | $prefix = $directory.TrimEnd('\') + '\' |
| 152 | $owned = @(Get-VM | Where-Object { |
| 153 | $_.Name -eq $Name -and ($_.Path -eq $directory -or $_.Path.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) |
| 154 | }) |
| 155 | foreach ($registered in $owned) { |
| 156 | if ($registered.State -ne 'Off') { throw "VM is running. Preserved '$directory': $creationError" } |
| 157 | Remove-VM -VM $registered -Force |
| 158 | } |
| 159 | # Remove-VM deals with its configuration and key protector. Delete only |
| 160 | # our disk and empty directories. Unexpected files stay available for recovery. |
| 161 | $root = Get-Item -LiteralPath $directory |
| 162 | if ($root.Attributes -band [IO.FileAttributes]::ReparsePoint) { |
| 163 | throw "Instance directory changed; preserved '$directory': $creationError" |
| 164 | } |
| 165 | [IO.File]::Delete($diskPath) |
| 166 | if ($ownsToolsISO) { [IO.File]::Delete($toolsISO) } |
| 167 | foreach ($child in $root.EnumerateDirectories()) { |
| 168 | if (!($child.Attributes -band [IO.FileAttributes]::ReparsePoint) -and |
| 169 | !@($child.EnumerateFileSystemInfos()).Count) { $child.Delete() } |
| 170 | } |
| 171 | if (!@($root.EnumerateFileSystemInfos()).Count) { $root.Delete() } |
| 172 | else { Write-Warning "Unexpected files retained at '$directory'." } |
| 173 | } |
| 174 | throw $creationError |
| 175 | } finally { |
| 176 | if ($staged) { [IO.Directory]::Delete($staging, $false) } |
| 177 | } |
| 178 | $result = [pscustomobject]@{ VMId = $vm.Id; Name = $vm.Name; InstanceDirectory = $directory; Disk = $diskPath } |
| 179 | if ($Start) { |
| 180 | try { Start-VM -VM $vm } catch { throw "Created VM $($vm.Id) at '$directory'; starting it failed: $_" } |
| 181 | } |
| 182 | $result |