---
title: Hyper-V VM Inventory
slug: hyper-v-vm-inventory
createdAt: 2025-04-07T22:53:53.156Z
---

Will work partially using localsystem, but will not work for VM files on network drives (NAS etc). For this, the script will have to be run as an administrator who has fill access to hyper-V and the network shares holding the VHDs.&#x20;

# Powershell

```powershell
#Requires -RunAsAdministrator

<#
.SYNOPSIS
    Retrieves detailed Hyper-V Virtual Machine inventory information using WMI/CIM.
.DESCRIPTION
    Queries the local Hyper-V host for VMs and gathers details including:
    - Basic VM Info (Name, ID, State)
    - Configuration (Memory, CPU)
    - Guest Info via KVP (OS, Hostname, IP Addresses, Integration Services Version)
    - Network Adapters (MAC, Switch)
    - Virtual Hard Drives (Path, Type, Configured Size, Actual Size, Access Status)
    Outputs the collected data as a JSON object.
    Includes enhanced handling for VHD file access, providing status notes
    especially when running as LocalSystem encountering network share permissions issues.
.NOTES
    Author: Based on user script and AI suggestions
    Date: 2025-04-07
    Requires: PowerShell v3+, Hyper-V Role installed, Administrator privileges.
              The Get-VHD cmdlet (part of Hyper-V PowerShell module) is used for VHD type detection.
    Running Context: Designed to run locally on the Hyper-V host. If run as LocalSystem,
                     network VHD file access requires the COMPUTERNAME$ account to have
                     permissions on the target network share and file system.
#>

# Define the Hyper-V WMI namespace
$namespace = "root\virtualization\v2"

# Define a mapping for EnabledState numerical values to readable strings
$enabledStateMap = @{
    0 = 'Unknown'
    2 = 'Running' # Enabled
    3 = 'Off'     # Disabled
    32768 = 'Paused'
    32769 = 'Suspended'
    32770 = 'Starting'
    32771 = 'Snapshotting'
    32773 = 'Saving'
    32774 = 'Stopping'
    32776 = 'Pausing'
    32777 = 'Resuming'
}

Write-Output "Attempting to retrieve VMs from WMI namespace '$namespace'..."

# Retrieve guest VMs (Msvm_ComputerSystem where Caption equals "Virtual Machine")
try {
    # Use a filter for potentially better performance than Where-Object after retrieval
    $vms = Get-CimInstance -Namespace $namespace -ClassName Msvm_ComputerSystem -Filter 'Caption = "Virtual Machine"' -ErrorAction Stop
} catch {
    Write-Error "Failed to retrieve VMs. Error: $($_.Exception.Message)"
    Write-Error "Ensure Hyper-V role is installed, the service is running, and you have necessary permissions (Run as Administrator)."
    exit 1
}

# Check if any VMs were found
if (-not $vms) {
    Write-Output "No VMs found. Ensure Hyper-V is installed, running, and VMs exist."
    exit
}

Write-Output "Found $($vms.Count) VMs. Processing each..."

# Initialize an array to store details for all VMs
$allVMInfo = @()

# Loop through each VM found
foreach ($vm in $vms) {
    $vmName = $vm.ElementName
    $vmID = $vm.Name # Typically the VM's GUID
    Write-Host "Processing VM: $vmName ($vmID)"

    try {
        # --- Basic VM details ---
        $stateNumber = $vm.EnabledState
        $enabledStateString = $enabledStateMap[$stateNumber] # Look up the readable state
        if (-not $enabledStateString) { $enabledStateString = "Unknown State ($stateNumber)" } # Handle unknown codes
        $creationTime = $vm.CreationTime

        # --- Retrieve VM Settings (Msvm_VirtualSystemSettingData) ---
        # Use Association: Msvm_SettingsDefineState links Msvm_ComputerSystem to Msvm_VirtualSystemSettingData
        $vmSettings = Get-CimAssociatedInstance -InputObject $vm -ResultClassName Msvm_VirtualSystemSettingData -ErrorAction Stop | Select-Object -First 1
        # Note: Assumes the first associated setting data is the active one. Complex snapshot scenarios might require more filtering.
        $vmNotes = if($vmSettings) {$vmSettings.Notes} else {$null}

        # --- Memory Configuration ---
        $memoryStartupMB = if ($vmSettings) { $vmSettings.MemoryStartup } else { $null } # In MB
        $dynamicMemoryEnabled = if ($vmSettings) { $vmSettings.DynamicMemoryEnabled } else { $null }
        $memoryMinimumMB = if ($vmSettings -and $dynamicMemoryEnabled) { $vmSettings.MemoryMinimum } else { $null } # In MB
        $memoryMaximumMB = if ($vmSettings -and $dynamicMemoryEnabled) { $vmSettings.MemoryMaximum } else { $null } # In MB

        # --- Processor Configuration ---
        $procSettings = $null
        if ($vmSettings) {
           # Use Association: Msvm_VirtualSystemSettingData to Msvm_ProcessorSettingData
           $procSettings = Get-CimAssociatedInstance -InputObject $vmSettings -ResultClassName Msvm_ProcessorSettingData -ErrorAction SilentlyContinue | Select-Object -First 1
        }
        $cpuCount = if ($procSettings) { $procSettings.VirtualQuantity } else { $null }
        $cpuLimit = if ($procSettings) { $procSettings.Limit } else { $null } # CPU Limit % (100000 = 100%)
        $cpuReservation = if ($procSettings) { $procSettings.Reservation } else { $null } # CPU Reservation % (Not % based, matches VirtualQuantity units)
        $cpuWeight = if ($procSettings) { $procSettings.Weight } else { $null } # Relative weight

        # --- Retrieve KVP Guest Data (Integration Services Data Exchange) ---
        $kvpData = @{}
        $guestOS = $null; $guestOSVersion = $null; $guestHostname = $null; $integrationVersion = $null; $networkAddressIPv4 = $null; $networkAddressIPv6 = $null

        try {
            # Use Association: Msvm_ComputerSystem to Msvm_KvpExchangeComponentData
            $kvpComponentData = Get-CimAssociatedInstance -InputObject $vm -ResultClassName Msvm_KvpExchangeComponentData -ErrorAction SilentlyContinue | Select-Object -First 1

            if ($kvpComponentData -and $kvpComponentData.GuestIntrinsicExchangeItems) {
                # Data is often XML containing key-value pairs within GuestIntrinsicExchangeItems
                $xmlData = [xml]$kvpComponentData.GuestIntrinsicExchangeItems
                $xmlData.Objs.Obj.Property | ForEach-Object {
                    if ($_.Name -and $_.'#') { # Ensure Name and Value exist
                         $kvpData[$_.Name] = $_.'#'
                    }
                }
                 # Extract common KVP keys safely
                $guestOS            = if ($kvpData.ContainsKey('OSName')) { $kvpData['OSName'] } else { $null }
                $guestOSVersion     = if ($kvpData.ContainsKey('OSVersion')) { $kvpData['OSVersion'] } else { $null }
                $guestHostname      = if ($kvpData.ContainsKey('FullyQualifiedDomainName')) { $kvpData['FullyQualifiedDomainName'] } elseif ($kvpData.ContainsKey('ComputerName')) { $kvpData['ComputerName'] } else { $null } # FQDN preferred
                $integrationVersion = if ($kvpData.ContainsKey('IntegrationServicesVersion')) { $kvpData['IntegrationServicesVersion'] } else { $null }
                $networkAddressIPv4 = if ($kvpData.ContainsKey('NetworkAddressIPv4')) { $kvpData['NetworkAddressIPv4'] } else { $null } # Often semi-colon separated
                $networkAddressIPv6 = if ($kvpData.ContainsKey('NetworkAddressIPv6')) { $kvpData['NetworkAddressIPv6'] } else { $null } # Often semi-colon separated

            } else {
                  Write-Warning "VM $vmName: KVP GuestIntrinsicExchangeItems not found or empty. Integration Services might be off, malfunctioning, or guest OS doesn't support."
            }
        } catch {
            Write-Warning "VM $vmName: Could not parse KVP data. Error: $($_.Exception.Message). Integration Services might be off or guest OS doesn't support."
        }


        # --- Retrieve Network Adapter Details ---
        $nicInfoArray = @()
        if ($vmSettings) {
            # Use Association from $vmSettings -> Msvm_ResourceAllocationSettingData (RASD) -> Msvm_SyntheticEthernetPortSettingData
            $ethernetRasds = Get-CimAssociatedInstance -InputObject $vmSettings -ResultClassName Msvm_ResourceAllocationSettingData -ErrorAction SilentlyContinue |
                                Where-Object { $_.ResourceType -eq 10 } # ResourceType 10 = Ethernet Adapter

            if ($ethernetRasds) {
                foreach ($rasd in $ethernetRasds) {
                    # Get the specific NIC settings associated with this resource allocation
                    $nicSetting = Get-CimAssociatedInstance -InputObject $rasd -ResultClassName Msvm_SyntheticEthernetPortSettingData -ErrorAction SilentlyContinue | Select-Object -First 1
                    if ($nicSetting) {
                         # Get connected switch name via Msvm_EthernetPortAllocationSettingData association
                         $portAllocation = Get-CimAssociatedInstance -InputObject $rasd -ResultClassName Msvm_EthernetPortAllocationSettingData -ErrorAction SilentlyContinue | Select-Object -First 1
                         $switchName = $null
                         if ($portAllocation -and $portAllocation.HostResource) {
                            # HostResource often contains the switch ID like 'Microsoft:Hyper-V:Virtual Ethernet Switch\{GUID}'
                            $switchName = $portAllocation.ElementName # Often descriptive, like the NIC name + Switch Name
                            # Could parse HostResource for GUID and look up Msvm_VirtualEthernetSwitch if ElementName isn't sufficient
                         }

                        $nicInfoArray += [PSCustomObject]@{
                            AdapterName = $nicSetting.ElementName
                            MACAddress  = $nicSetting.Address
                            IsStaticMac = $nicSetting.StaticMacAddress
                            SwitchName  = $switchName # Name of the vSwitch connected to (or associated port allocation name)
                        }
                    }
                }
            }
        }

        # --- Retrieve Virtual Hard Drive Details (Enhanced Handling) ---
        # Use Association from $vmSettings -> Msvm_ResourceAllocationSettingData (RASD) -> Msvm_StorageAllocationSettingData (SASD)
        $virtualHardDrives = @()
        if ($vmSettings) {
            # Find Resource Allocation Settings associated with storage
            $diskRasds = Get-CimAssociatedInstance -InputObject $vmSettings -ResultClassName Msvm_ResourceAllocationSettingData -ErrorAction SilentlyContinue |
                            Where-Object { $_.ResourceSubType -like "*Virtual Hard Disk*" -or $_.ResourceType -in (17, 21, 31) } # Check ResourceSubType first, then common ResourceTypes

            if ($diskRasds) {
                foreach ($rasd in $diskRasds) {
                    # Get storage allocation details associated with this resource
                    $storageSetting = Get-CimAssociatedInstance -InputObject $rasd -ResultClassName Msvm_StorageAllocationSettingData -ErrorAction SilentlyContinue | Select-Object -First 1

                    # Ensure it's specifically a Virtual Hard Disk type we are interested in
                    if ($storageSetting -and $storageSetting.ResourceSubType -eq "Microsoft:Hyper-V:Virtual Hard Disk") {
                        $filePath = $null
                        # Get path from WMI configuration (doesn't require file access permission)
                        if ($storageSetting.HostResource -and $storageSetting.HostResource.Count -gt 0) {
                             $filePath = $storageSetting.HostResource[0] # Primary location for path
                        }
                        if (-not $filePath -and $rasd.Connection -and $rasd.Connection.Count -gt 0) {
                            $filePath = $rasd.Connection[0] # Fallback location for path
                        }

                        # Initialize variables for details and status
                        $configuredSizeGB = if ($storageSetting.VirtualQuantity) { [math]::Round($storageSetting.VirtualQuantity / 1GB, 2) } else { $null } # Max size from WMI
                        $actualFileSizeGB = $null # Actual size on disk, null initially
                        $vhdType = $null # Type (Fixed, Dynamic, Differencing)
                        $accessStatus = "Unknown" # Default file access status
                        $parentPath = $rasd.Parent # Check for differencing disk via parent property in WMI

                        # Proceed only if we have a path from WMI configuration
                        if ($filePath) {
                            $isNetworkPath = $filePath.StartsWith("\\")
                            $pathExistsOrAccessible = $false # Assume not accessible initially

                            # 1. Attempt Test-Path (Checks existence AND accessibility at a basic level)
                            try {
                                # Use -PathType Leaf to ensure it checks for a file, not just the directory path
                                $pathExistsOrAccessible = Test-Path -Path $filePath -PathType Leaf -ErrorAction Stop
                                # If Test-Path is $true, we likely have *some* level of access (e.g., read attributes)
                            } catch {
                                # Test-Path failed, could be permissions, offline share, typo, or truly non-existent
                                $pathExistsOrAccessible = $false
                                $errorMessage = $_.Exception.Message
                                if ($isNetworkPath) {
                                    $accessStatus = "Path Inaccessible (Network Path - Check Permissions/Connectivity)"
                                    Write-Warning "VM $vmName: Cannot access network VHD path '$filePath'. Likely permission issue for computer account '$($env:COMPUTERNAME)$' or offline share. Error: $errorMessage"
                                } else {
                                    $accessStatus = "Path Not Found or Inaccessible (Local Path)"
                                     Write-Warning "VM $vmName: Cannot access local VHD path '$filePath'. Error: $errorMessage"
                                }
                            }

                            # 2. Attempt to Get VHD Type (only if path seems accessible or it's differencing)
                            if ($parentPath) {
                                $vhdType = "Differencing"
                                # No need to call Get-VHD if we know it's differencing based on Parent property from WMI
                                # Set status based on Test-Path result if it wasn't already set to an error
                                if ($accessStatus -eq "Unknown") {
                                    $accessStatus = if ($pathExistsOrAccessible) {"OK (Differencing)"} else {"Path Inaccessible (Differencing)"}
                                } elseif ($accessStatus -like "*Inaccessible*") {
                                    # Keep inaccessible status but clarify type
                                     $accessStatus += " (Differencing)"
                                }

                            } elseif ($pathExistsOrAccessible) {
                                # Path seems accessible, try Get-VHD for type (Fixed/Dynamic) - Requires Hyper-V Module
                                try {
                                    $vhdInfo = Get-VHD -Path $filePath -ErrorAction Stop
                                    if ($vhdInfo) {
                                        $vhdType = $vhdInfo.VhdType # e.g., Fixed, Dynamic
                                        # Only set status to OK if Get-VHD succeeded *and* we haven't hit other errors
                                        if ($accessStatus -eq 'Unknown') { $accessStatus = "OK" }
                                    } else {
                                         $vhdType = "Unknown (Get-VHD returned no data)"
                                         if ($accessStatus -eq 'Unknown') { $accessStatus = "Read Warning (Get-VHD)" }
                                    }
                                } catch {
                                    $vhdType = "Unknown (Get-VHD Failed)"
                                    $errorMessage = $_.Exception.Message
                                    Write-Warning "VM $vmName: Get-VHD failed for '$filePath'. May require Hyper-V PS module loaded and sufficient file permissions. Error: $errorMessage"
                                    if ($accessStatus -eq 'Unknown') {
                                         $accessStatus = "Read Error (Get-VHD)"
                                         if ($isNetworkPath) { $accessStatus += " (Network Path?)"}
                                    }
                                }
                            } else {
                                # Path is not accessible/found, cannot determine type beyond Differencing check above
                                if ($vhdType -ne "Differencing") { # Don't overwrite if already identified as differencing
                                    $vhdType = "Unknown (Path Not Accessible)"
                                }
                                # accessStatus should already be set from Test-Path failure
                            }


                            # 3. Attempt to Get Actual File Size (only if path seems accessible via Test-Path)
                            if ($pathExistsOrAccessible) {
                                try {
                                    $fileItem = Get-Item $filePath -ErrorAction Stop
                                    $actualFileSizeGB = [math]::Round($fileItem.Length / 1GB, 2)
                                    # Set status to OK only if this succeeds and no prior error set status
                                    if ($accessStatus -eq 'Unknown' -or $accessStatus -like "OK*") { $accessStatus = "OK" }
                                } catch {
                                    $errorMessage = $_.Exception.Message
                                    Write-Warning "VM $vmName: Error reading file size for '$filePath' using Get-Item. Error: $errorMessage"
                                    $actualFileSizeGB = $null # Ensure size is null on error
                                    # Update status if not already an error, or if was previously OK but Get-Item failed
                                    if ($accessStatus -eq 'Unknown' -or $accessStatus -like "OK*") {
                                         $accessStatus = "Read Error (Get-Item)"
                                         if ($isNetworkPath) { $accessStatus += " (Network Path?)"}
                                    }
                                }
                            } else {
                                # Path not accessible/found, cannot get actual size
                                $actualFileSizeGB = $null
                                # accessStatus should already be set from Test-Path failure
                            }

                        } else {
                            # No file path could be determined from WMI configuration for this storage resource
                            $accessStatus = "Path Not Configured in WMI"
                            Write-Warning "VM $vmName: Could not determine VHD file path from WMI for a disk resource (RASD: $($rasd.InstanceID))."
                        }

                        # Add the gathered VHD info, including the file access status
                        $virtualHardDrives += [PSCustomObject]@{
                            FilePath         = $filePath         # The configured path from WMI
                            ParentPath       = $parentPath        # Path to parent disk if differencing (from WMI)
                            VHDType          = $vhdType           # Best guess type (Differencing, Dynamic, Fixed, or Unknown/Error)
                            ConfiguredSizeGB = $configuredSizeGB  # Max size from WMI (Bytes converted to GB)
                            ActualFileSizeGB = $actualFileSizeGB  # Actual size on disk (GB), or $null if inaccessible/error
                            AddressOnParent  = $rasd.AddressOnParent # Controller location (e.g., 0, 1) from WMI
                            AccessStatus     = $accessStatus      # Status of attempts to access the file ("OK", "Inaccessible (Network Path?)", "Read Error", etc.)
                        }
                    } # End if ($storageSetting and type is VHD)
                } # End foreach ($rasd in $diskRasds)
            } # End if ($diskRasds)
        } # End if ($vmSettings)

        # --- Compose the final object for this VM ---
        $vmDetail = [PSCustomObject]@{
            VMName             = $vmName
            VMID               = $vmID
            State              = $enabledStateString
            CreationTime       = $creationTime
            Notes              = $vmNotes
            MemoryStartupMB    = $memoryStartupMB
            DynamicMemoryEnabled = $dynamicMemoryEnabled
            MemoryMinimumMB    = $memoryMinimumMB # Only relevant if Dynamic Memory is On
            MemoryMaximumMB    = $memoryMaximumMB # Only relevant if Dynamic Memory is On
            CPUCount           = $cpuCount
            CPULimitPercent    = if($cpuLimit) { $cpuLimit / 1000 } else {$null} # Convert 100000 -> 100%
            CPUReservation     = $cpuReservation # Matches VirtualQuantity units, not percentage based like Limit. Usually correlates to #CPUs
            CPUWeight          = $cpuWeight # Relative weight for CPU scheduler
            GuestOS            = $guestOS
            GuestOSVersion     = $guestOSVersion
            GuestHostname      = $guestHostname
            IntegrationVersion = $integrationVersion
            NetworkAddressIPv4 = $networkAddressIPv4 # Semicolon separated if multiple IPs reported by KVP
            NetworkAddressIPv6 = $networkAddressIPv6 # Semicolon separated if multiple IPs reported by KVP
            NetworkAdapters    = $nicInfoArray       # Array of NIC objects
            VirtualHardDrives  = $virtualHardDrives   # Array of VHD objects with enhanced status
            HyperVHost         = $env:COMPUTERNAME # Record which host this was run on
        }

        # Add the details for this VM to the main array
        $allVMInfo += $vmDetail

    } catch {
        # Catch errors during processing of a single VM
        Write-Error "Failed to process VM '$vmName' ($vmID). Error at $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)"
        # Add a placeholder object indicating the failure for this VM
        $allVMInfo += [PSCustomObject]@{
            VMName     = $vmName
            VMID       = $vmID
            State      = "Error Processing"
            Error      = $_.Exception.Message
            HyperVHost = $env:COMPUTERNAME
        }
    }
} # End foreach VM loop

Write-Output "Finished processing VMs."

# --- Output Generation ---

# Convert the final results array to JSON format
# Increase depth if necessary, 5 is usually sufficient for this structure
$jsonOutput = $allVMInfo | ConvertTo-Json -Depth 5 -Compress # Use -Compress for smaller output string

# Output the JSON string to the console (or pipeline)
Write-Output $jsonOutput

# --- Optional: Save JSON to a file ---
# $jsonFilePath = "C:\ProgramData\HyperVInventory\$(Get-Date -Format 'yyyyMMddHHmmss')_HyperVInventory.json"
# # Ensure directory exists
# $jsonDirPath = Split-Path $jsonFilePath -Parent
# if (-not (Test-Path $jsonDirPath)) {
#     New-Item -ItemType Directory -Path $jsonDirPath -Force | Out-Null
# }
# try {
#     $jsonOutput | Out-File -FilePath $jsonFilePath -Encoding UTF8 -ErrorAction Stop
#      Write-Host "Inventory JSON saved to: $jsonFilePath"
# } catch {
#      Write-Error "Failed to save JSON to '$jsonFilePath'. Error: $($_.Exception.Message)"
# }


# --- Database Insertion (Conceptual Example - Needs SQLite Module like PSSQLite) ---
# This section remains commented out as it requires external modules and setup.
# The JSON output above can be used as input for a separate database insertion process.

# $dbPath = "C:\ProgramData\HyperVInventory\HyperVInventory.sqlite"
# $sqliteModule = "PSSQLite" # Or Microsoft.Data.Sqlite

# if (Get-Command Invoke-SqliteQuery -Module $sqliteModule -ErrorAction SilentlyContinue) {
#     # ... (Code for Table Creation - IF NOT EXISTS recommended) ...
#     # ... (Code for Looping through $allVMInfo) ...
#     #     ... (Code for UPSERT into VMs table) ...
#     #     ... (Code for DELETE/INSERT into VM_NetworkAdapters table) ...
#     #     ... (Code for DELETE/INSERT into VM_VHDs table, using the $vhd.AccessStatus field) ...
#     Write-Host "Database operations would occur here."
# } else {
#     Write-Warning "SQLite module ('$sqliteModule') not found or command 'Invoke-SqliteQuery' unavailable. Skipping direct database operations."
# }

Write-Host "Script finished."
```



# Database Tables for VM Inventory

**Table:&#x20;**`VMs`

Stores core information for each discovered Virtual Machine. (This table is the target of Foreign Keys).

| Column Name              | Data Type  | Constraints            | Description                                                        |
| ------------------------ | ---------- | ---------------------- | ------------------------------------------------------------------ |
| `VMID`                   | `TEXT`     | `PRIMARY KEY NOT NULL` | Unique GUID of the Virtual Machine.                                |
| `VMName`                 | `TEXT`     |                        | User-defined name of the VM.                                       |
| `State`                  | `TEXT`     |                        | Current operational state (e.g., "Running", "Off").                |
| `CreationTime`           | `DATETIME` |                        | Timestamp when the VM was created.                                 |
| `Notes`                  | `TEXT`     |                        | VM Notes/Description field from Hyper-V settings.                  |
| `MemoryStartupMB`        | `INTEGER`  |                        | Assigned Startup Memory in Megabytes.                              |
| `DynamicMemoryEnabled`   | `INTEGER`  |                        | Boolean (0 or 1) indicating if Dynamic Memory is enabled.          |
| `MemoryMinimumMB`        | `INTEGER`  |                        | Minimum Dynamic Memory in MB (if enabled).                         |
| `MemoryMaximumMB`        | `INTEGER`  |                        | Maximum Dynamic Memory in MB (if enabled).                         |
| `CPUCount`               | `INTEGER`  |                        | Number of virtual CPUs assigned.                                   |
| `CPULimitPercent`        | `REAL`     |                        | CPU usage limit as a percentage (e.g., 100.0, 75.5).               |
| `CPUReservation`         | `INTEGER`  |                        | Reserved CPU resources (matches vCPU units, not percentage).       |
| `CPUWeight`              | `INTEGER`  |                        | Relative CPU scheduling weight.                                    |
| `GuestOS`                | `TEXT`     |                        | Guest Operating System Name reported by KVP (if available).        |
| `GuestOSVersion`         | `TEXT`     |                        | Guest OS Version reported by KVP (if available).                   |
| `GuestHostname`          | `TEXT`     |                        | Guest Hostname/FQDN reported by KVP (if available).                |
| `IntegrationVersion`     | `TEXT`     |                        | Integration Services version reported by KVP (if available).       |
| `NetworkAddressIPv4`     | `TEXT`     |                        | IPv4 addresses reported by KVP (semi-colon separated if multiple). |
| `NetworkAddressIPv6`     | `TEXT`     |                        | IPv6 addresses reported by KVP (semi-colon separated if multiple). |
| `HyperVHost`             | `TEXT`     | `NOT NULL`             | Name of the Hyper-V host where the VM was found.                   |
| `LastInventoryTimestamp` | `DATETIME` | `NOT NULL`             | Timestamp when this record was last inserted or updated.           |

***

**Table:&#x20;**`VM_NetworkAdapters`

Stores information about each Network Interface Controller (NIC) associated with a VM.

| Column Name   | Data Type | Constraints                                        | Description                                                         |
| ------------- | --------- | -------------------------------------------------- | ------------------------------------------------------------------- |
| `MACAddress`  | `TEXT`    | `PRIMARY KEY NOT NULL`                             | MAC Address of the virtual NIC (usually unique per host).           |
| `VMID`        | `TEXT`    | `NOT NULL, FOREIGN KEY(VMID) REFERENCES VMs(VMID)` | Links this NIC back to the specific VM in the `VMs` table.          |
| `AdapterName` | `TEXT`    |                                                    | Name of the network adapter within the VM settings.                 |
| `IsStaticMac` | `INTEGER` |                                                    | Boolean (0 or 1) indicating if the MAC address is statically set.   |
| `SwitchName`  | `TEXT`    |                                                    | Name of the virtual switch or port allocation this NIC connects to. |

*Note: Using&#x20;*`MACAddress`*&#x20;as a primary key assumes MAC addresses are unique across all inventoried VMs on a host. If duplicates are possible in your environment (e.g., disconnected NICs with same static MAC on different VMs), you might consider a composite primary key like&#x20;*`(VMID, MACAddress)`*&#x20;or&#x20;*`(VMID, AdapterName)`*.*

***

**Table:&#x20;**`VM_VHDs`

Stores information about each Virtual Hard Drive (VHD/VHDX) associated with a VM.

| Column Name        | Data Type | Constraints                                        | Description                                                                           |
| ------------------ | --------- | -------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `FilePath`         | `TEXT`    | `PRIMARY KEY NOT NULL`                             | Configured path to the VHD/VHDX file.                                                 |
| `VMID`             | `TEXT`    | `NOT NULL, FOREIGN KEY(VMID) REFERENCES VMs(VMID)` | Links this VHD back to the specific VM in the `VMs` table.                            |
| `ParentPath`       | `TEXT`    |                                                    | Path to the parent disk (for differencing disks only).                                |
| `VHDType`          | `TEXT`    |                                                    | Type of VHD (e.g., "Fixed", "Dynamic", "Differencing", "Unknown...").                 |
| `ConfiguredSizeGB` | `REAL`    |                                                    | Maximum configured size of the VHD in Gigabytes.                                      |
| `ActualFileSizeGB` | `REAL`    |                                                    | Actual size of the VHD file on disk in Gigabytes (if accessible).                     |
| `AddressOnParent`  | `TEXT`    |                                                    | Location on the controller (e.g., "0,0", "1,0").                                      |
| `AccessStatus`     | `TEXT`    |                                                    | Status indicating accessibility ("OK", "Inaccessible (Network Path?)", "Read Error"). |

*Note: Using&#x20;*`FilePath`*&#x20;as a primary key assumes file paths are unique for configured VHDs across the host inventory. If multiple VMs could genuinely point to the exact same file path string (unlikely but possible), consider a composite key like&#x20;*`(VMID, FilePath)`*.*

***

*General Note: Consider adding indexes on Foreign Key columns (*`VMID`*&#x20;in&#x20;*`VM_NetworkAdapters`*&#x20;and&#x20;*`VM_VHDs`*) and other frequently queried columns (e.g.,&#x20;*`VMName`*,&#x20;*`HyperVHost`*&#x20;in&#x20;*`VMs`*) to optimize query performance.*
