| 1 | $ErrorActionPreference = 'Stop' |
| 2 | $ProgressPreference = 'SilentlyContinue' |
| 3 | $WarningPreference = 'SilentlyContinue' |
| 4 | [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) |
| 5 | # An exact CIM query can return zero matches without conflating a failed or |
| 6 | # unauthorized management request with a nonexistent VM. |
| 7 | $systems = @(Get-CimInstance -Namespace root/virtualization/v2 -ClassName Msvm_ComputerSystem -Filter "Name='$targetId'") |
| 8 | if ($systems.Count -eq 0) { Write-Output 'null'; return } |
| 9 | if ($systems.Count -ne 1) { throw 'Unexpected Hyper-V management result.' } |
| 10 | $vm = Hyper-V\Get-VM -Id $targetId |
| 11 | if ($vm.Id -ne $targetId -or [string]::IsNullOrWhiteSpace([string]$vm.State) -or $vm.Generation -notin 1,2) { |
| 12 | throw 'Hyper-V instance changed.' |
| 13 | } |
| 14 | $disks = @(Hyper-V\Get-VMHardDiskDrive -VM $vm) |
| 15 | $adapters = @(Hyper-V\Get-VMNetworkAdapter -VM $vm) |
| 16 | $singleLocalVHDX = $false |
| 17 | $diskType = '' |
| 18 | if ($disks.Count -eq 1 -and $disks[0].Path) { |
| 19 | $path = [string]$disks[0].Path |
| 20 | if ($path -match '^[A-Za-z]:[\\/]') { |
| 21 | try { |
| 22 | if ([IO.DriveInfo]::new($path.Substring(0,3)).DriveType -ne 'Network') { |
| 23 | $disk = Hyper-V\Get-VHD -Path $path |
| 24 | if (!$disk -or !$disk.VhdFormat) { throw 'No local VHD metadata.' } |
| 25 | $singleLocalVHDX = [string]$disk.VhdFormat -eq 'VHDX' |
| 26 | $diskType = [string]$disk.VhdType |
| 27 | } |
| 28 | } catch { |
| 29 | $singleLocalVHDX = $null |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | $secureBoot = $false |
| 34 | $template = '' |
| 35 | $virtualTPM = $false |
| 36 | if ($vm.Generation -eq 2) { |
| 37 | $firmware = Hyper-V\Get-VMFirmware -VM $vm |
| 38 | $security = Hyper-V\Get-VMSecurity -VM $vm |
| 39 | if ($null -eq $security.TpmEnabled -or [string]$firmware.SecureBoot -notin 'On','Off') { throw 'Incomplete security configuration.' } |
| 40 | $secureBoot = [string]$firmware.SecureBoot -eq 'On' |
| 41 | $template = [string]$firmware.SecureBootTemplate |
| 42 | $virtualTPM = [bool]$security.TpmEnabled |
| 43 | } |
| 44 | [ordered]@{ |
| 45 | state=[string]$vm.State; generation=[int]$vm.Generation |
| 46 | diskCount=$disks.Count; singleLocalVhdx=$singleLocalVHDX; diskType=$diskType |
| 47 | secureBoot=$secureBoot; secureBootTemplate=$template; virtualTpm=$virtualTPM |
| 48 | networkAdapterCount=$adapters.Count |
| 49 | } | ConvertTo-Json -Compress |