| 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 'Binding unavailable.' } |
| 6 | if ($action -eq 'start') { |
| 7 | if ($vm.Generation -ne 2) { throw 'Guest generation unavailable.' } |
| 8 | $firmware = Hyper-V\Get-VMFirmware -VM $vm |
| 9 | $security = Hyper-V\Get-VMSecurity -VM $vm |
| 10 | if ([string]$firmware.SecureBoot -ne 'On' -or [string]$firmware.SecureBootTemplate -ne 'MicrosoftWindows' -or $security.TpmEnabled -ne $true) { throw 'Guest security unavailable.' } |
| 11 | # Until Cage's managed exit has a Windows adapter, this guest remains offline. |
| 12 | if (@(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0) { throw 'Controlled exit unavailable.' } |
| 13 | if ([string]$vm.State -eq 'Off') { Hyper-V\Start-VM -VM $vm | Out-Null } |
| 14 | elseif ([string]$vm.State -ne 'Running') { throw 'Guest cannot be started from this state.' } |
| 15 | } elseif ($action -eq 'stop') { |
| 16 | if ([string]$vm.State -eq 'Running') { |
| 17 | # Stop-VM without TurnOff/Force requests the guest shutdown integration service. |
| 18 | Hyper-V\Stop-VM -VM $vm -ErrorAction Stop | Out-Null |
| 19 | } elseif ([string]$vm.State -ne 'Off') { throw 'Guest cannot be stopped safely from this state.' } |
| 20 | } else { throw 'Invalid operation.' } |
| 21 | $vm = Hyper-V\Get-VM -Id $targetId |
| 22 | if (!$vm -or $vm.Id -ne $targetId) { throw 'Binding changed.' } |
| 23 | [ordered]@{state=[string]$vm.State} | ConvertTo-Json -Compress |