| 1 | $ErrorActionPreference='Stop' |
| 2 | $ProgressPreference='SilentlyContinue' |
| 3 | [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) |
| 4 | $vm=Hyper-V\Get-VM -Id $targetId |
| 5 | if(!$vm -or $vm.Id -ne $targetId){throw 'Bound VM unavailable.'} |
| 6 | $memory=Hyper-V\Get-VMMemory -VM $vm |
| 7 | $processor=Hyper-V\Get-VMProcessor -VM $vm |
| 8 | if($memoryGiB -ne 0 -or $cpus -ne 0){ |
| 9 | if($memoryGiB -lt 4 -or $memoryGiB -gt 1024 -or $cpus -lt 1 -or $cpus -gt 1024 -or [string]$vm.State -ne 'Off'){throw 'Stop the guest before applying Windows 11 resources.'} |
| 10 | $maximum=[int64]$memoryGiB*1GB |
| 11 | try{ |
| 12 | Hyper-V\Set-VMProcessor -VM $vm -Count $cpus |
| 13 | Hyper-V\Set-VMMemory -VM $vm -DynamicMemoryEnabled $true -MinimumBytes 4GB -StartupBytes 4GB -MaximumBytes $maximum |
| 14 | }catch{ |
| 15 | # Restore only the same VM's prior resource settings; keep its disk untouched. |
| 16 | try{Hyper-V\Set-VMProcessor -VM $vm -Count $processor.Count}catch{} |
| 17 | try{Hyper-V\Set-VMMemory -VM $vm -DynamicMemoryEnabled $memory.DynamicMemoryEnabled -MinimumBytes $memory.Minimum -StartupBytes $memory.Startup -MaximumBytes $memory.Maximum}catch{} |
| 18 | throw |
| 19 | } |
| 20 | $vm=Hyper-V\Get-VM -Id $targetId |
| 21 | if(!$vm -or $vm.Id -ne $targetId){throw 'Bound VM changed.'} |
| 22 | $memory=Hyper-V\Get-VMMemory -VM $vm |
| 23 | $processor=Hyper-V\Get-VMProcessor -VM $vm |
| 24 | } |
| 25 | [ordered]@{state=[string]$vm.State;cpus=[int]$processor.Count;memory_startup_bytes=[uint64]$memory.Startup;memory_minimum_bytes=[uint64]$memory.Minimum;memory_maximum_bytes=[uint64]$memory.Maximum;memory_assigned_bytes=[uint64]$vm.MemoryAssigned;dynamic_memory=[bool]$memory.DynamicMemoryEnabled}|ConvertTo-Json -Compress |