| 1 | param([Parameter(Mandatory)][string]$Query) |
| 2 | $ErrorActionPreference='Stop' |
| 3 | $script:targetId=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682' |
| 4 | $script:state='Off';$script:nics=0;$script:mutations=0;$script:generation=2;$script:secure='On' |
| 5 | New-Module -Name Hyper-V -ScriptBlock { |
| 6 | function Get-VM { param([Guid]$Id) if ($Id -ne $script:targetId) { throw 'Unscoped VM operation.' }; [pscustomobject]@{Id=$Id;State=$script:state;Generation=$script:generation} } |
| 7 | function Get-VMFirmware { param($VM) if ($VM.Id -ne $script:targetId) { throw 'Wrong VM.' };[pscustomobject]@{SecureBoot=$script:secure;SecureBootTemplate='MicrosoftWindows'} } |
| 8 | function Get-VMSecurity { param($VM) [pscustomobject]@{TpmEnabled=$true} } |
| 9 | function Get-VMNetworkAdapter { param($VM) for($i=0;$i -lt $script:nics;$i++){[pscustomobject]@{Id=$i}} } |
| 10 | function Start-VM { param($VM) if($VM.Id -ne $script:targetId){throw 'Wrong VM.'};$script:state='Running';$script:mutations++ } |
| 11 | function Stop-VM { param($VM,[switch]$TurnOff,[switch]$Force) if($TurnOff -or $Force -or $VM.Id -ne $script:targetId){throw 'Unsafe stop.'};$script:state='Off';$script:mutations++ } |
| 12 | Export-ModuleMember -Function * |
| 13 | } | Import-Module -Force |
| 14 | # Module state is independent: configure it deliberately for each case. |
| 15 | $module=Get-Module Hyper-V |
| 16 | & $module { $script:targetId=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682';$script:state='Off';$script:nics=0;$script:mutations=0;$script:generation=2;$script:secure='On' } |
| 17 | $action='start';$result=(& $Query)|ConvertFrom-Json |
| 18 | if($result.state -ne 'Running'){throw 'Start failed.'} |
| 19 | $action='stop';$result=(& $Query)|ConvertFrom-Json |
| 20 | if($result.state -ne 'Off'){throw 'Stop failed.'} |
| 21 | $action='stop';$result=(& $Query)|ConvertFrom-Json |
| 22 | if((& $module {$script:mutations}) -ne 2){throw 'Non-idempotent stop.'} |
| 23 | foreach($unsafe in 'nic','generation','secure'){ |
| 24 | & $module { $script:nics=0;$script:generation=2;$script:secure='On' } |
| 25 | switch($unsafe){'nic'{& $module {$script:nics=1}}'generation'{& $module {$script:generation=1}}'secure'{& $module {$script:secure='Off'}}} |
| 26 | $action='start';$rejected=$false;try{& $Query | Out-Null}catch{$rejected=$true} |
| 27 | if(!$rejected -or (& $module {$script:mutations}) -ne 2){throw "Unsafe $unsafe guest started."} |
| 28 | } |
| 29 | 'Windows lifecycle exact VM and safe shutdown checks passed.' |