modules/AzStack.Insights/AzStack.Insights.Helper.psm1

<################################################################
# #
# Copyright (C) Microsoft Corporation. All rights reserved. #
# #
################################################################>


function Get-InsightModulePaths {
    <#
    .SYNOPSIS
        Returns the resolved paths for the module root and packages directory.
    .DESCRIPTION
        Derives paths from the module file's own $PSScriptRoot, which PowerShell binds
        at module load time and cannot be overwritten by script code. Prefer this over
        reading from a global variable, which can be overwritten at runtime.
    .OUTPUTS
        PSCustomObject with ModuleRoot and PackagesPath properties.
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param()

    # $PSScriptRoot here is always the AzStack.Insights module directory
    # (modules\AzStack.Insights\), so two levels up reaches the version root.
    $moduleRoot   = (Get-Item -Path (Join-Path -Path $PSScriptRoot -ChildPath '..\..') -ErrorAction Stop).FullName
    $packagesPath = Join-Path -Path $moduleRoot -ChildPath 'packages'

    return [PSCustomObject]@{
        ModuleRoot   = $moduleRoot
        PackagesPath = $packagesPath
    }
}

function Get-ParsedFileVersion {
    <#
    .SYNOPSIS
        Returns a parsed System.Version value from a file's version metadata.
    .DESCRIPTION
        Reads FileVersion first, then ProductVersion, and extracts a numeric
        version token (for example, 1.2.3.4). Returns $null when no version can
        be parsed.
    .PARAMETER FilePath
        Path to the file whose version should be parsed.
    .OUTPUTS
        System.Version or $null.
    #>

    [CmdletBinding()]
    [OutputType([System.Version])]
    param(
        [Parameter(Mandatory = $true)]
        [string]$FilePath
    )

    $versionInfo = (Get-Item -Path $FilePath -ErrorAction Stop).VersionInfo
    $rawVersion = $versionInfo.FileVersion

    if ([string]::IsNullOrWhiteSpace($rawVersion)) {
        $rawVersion = $versionInfo.ProductVersion
    }

    if ([string]::IsNullOrWhiteSpace($rawVersion)) {
        return $null
    }

    $versionMatch = [System.Text.RegularExpressions.Regex]::Match($rawVersion, '\d+(\.\d+){1,3}')
    if (-not $versionMatch.Success) {
        return $null
    }

    try {
        return [System.Version]$versionMatch.Value
    }
    catch {
        return $null
    }
}

function Test-isFailoverCluster {
    [CmdletBinding()]
    param()
    # Detecting Failover Cluster based on the presence of the Get-Cluster cmdlet
    return ((Get-Command "Get-Cluster" -ErrorAction Ignore) -and (Get-Cluster -ErrorAction Ignore))
}

function Get-NodeFqdn {
    <#
    .SYNOPSIS
        Resolves the local node FQDN with resilient fallback behavior.
    .DESCRIPTION
        Uses Win32_ComputerSystem identity first, then DNS host lookup,
        then USERDNSDOMAIN, and finally falls back to computer name.
    #>

    [CmdletBinding()]
    param()

    $computerSystem = Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction SilentlyContinue
    if ($null -ne $computerSystem -and
        $computerSystem.PartOfDomain -and
        -not [string]::IsNullOrWhiteSpace($computerSystem.DNSHostName) -and
        -not [string]::IsNullOrWhiteSpace($computerSystem.Domain) -and
        $computerSystem.Domain -ne 'WORKGROUP') {
        return "$($computerSystem.DNSHostName).$($computerSystem.Domain)"
    }

    try {
        $hostName = [System.Net.Dns]::GetHostEntry($Env:ComputerName).HostName
        if (-not [string]::IsNullOrWhiteSpace($hostName) -and $hostName.Contains('.')) {
            return $hostName
        }
    }
    catch {
    }

    if (-not [string]::IsNullOrWhiteSpace($Env:USERDNSDOMAIN)) {
        return "$($Env:ComputerName).$($Env:USERDNSDOMAIN)"
    }

    return $Env:ComputerName
}

function Get-FirewallEndpoints {
    <#
    .SYNOPSIS
        Retrieves the required firewall endpoints for a specified Azure region.
 
    .DESCRIPTION
        This function returns a collection of firewall endpoints that need to be opened
        for Azure Local operations in the specified region. This comes from https://learn.microsoft.com/en-us/azure/azure-local/concepts/system-requirements-23h2?view=azloc-2601&tabs=azure-public
 
    .OUTPUTS
        Collection of PSObjects representing firewall endpoints.
 
    .EXAMPLE
        $endpoints = Get-FirewallEndpoints -Region 'eastus'
        Retrieves all firewall endpoints for the 'eastus' region and stores them in the $endpoints variable.
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Region
    )

    $endpointRootDir = Get-Item -Path "$PSScriptRoot\config\firewall_endpoints"
    try {
        switch ($Region) {
            'australiaeast' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "AustraliaEastEndpoints.psd1")
            }
            'canadacentral' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "CanadaCentralEndpoints.psd1")
            }
            'eastus' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "EastUSEndpoints.psd1")
            }
            'centralindia' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "IndiaCentralEndpoints.psd1")
            }
            'japaneast' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "JapanEastEndpoints.psd1")
            }
            'southcentralus' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "SouthCentralUSEndpoints.psd1")
            }
            'southeastasia' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "SoutheastAsiaEndpoints.psd1")
            }
            'westeurope' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "WestEuropeEndpoints.psd1")
            }
            'usgovvirginia' {
                $configData = Import-PowerShellDataFile -Path (Join-Path -Path $endpointRootDir.FullName -ChildPath "USGovVirginiaEndpoints.psd1")
            }
            default {
                return $null
            }
        }

        return $configData.Endpoints
    }
    catch {
        throw "Failed to load firewall endpoints for region '$Region'. $_"
    }
}

function Get-MocConfigCached {
    <#
    .SYNOPSIS
        Returns MOC configuration, using the global cache when available.
    .DESCRIPTION
        Reads from $Global:MocArbCachedMocConfig if populated (set by the
        MocArb component). On cache miss, calls Get-MocConfig
        directly with up to 5 retry attempts and exponential backoff to
        handle transient MOC file lock errors on the shared catalogs file.
    .PARAMETER CallerName
        Label used in diagnostic messages.
    .OUTPUTS
        The MOC configuration object, or $null if all attempts fail.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$CallerName = 'MocArb'
    )

    if ($Global:MocArbCachedMocConfig) {
        return $Global:MocArbCachedMocConfig
    }

    Write-Verbose "[$env:COMPUTERNAME][$CallerName] Cache miss, calling Get-MocConfig directly"
    $mocConfig = $null
    for ($attempt = 1; $attempt -le 5; $attempt++) {
        try { $mocConfig = Get-MocConfig -ErrorAction SilentlyContinue 2>$null } catch { }
        if ($mocConfig) {
            Write-Verbose "[$env:COMPUTERNAME][$CallerName] Get-MocConfig succeeded on attempt $attempt"
            return $mocConfig
        }
        if ($attempt -lt 5) {
            $backoff = 2 * $attempt
            Write-Warning "[$env:COMPUTERNAME][$CallerName] Get-MocConfig attempt $attempt failed, retrying in ${backoff}s"
            Start-Sleep -Seconds $backoff
        }
    }

    Write-Warning "[$env:COMPUTERNAME][$CallerName] Get-MocConfig failed after 5 attempts"
    return $null
}

function Get-ArbControlPlaneVMs {
    <#
    .SYNOPSIS
        Returns local Hyper-V VM objects for the ARB control-plane VM.
    .DESCRIPTION
        Calls Get-VM -Name '*control-plan*' on the local node, then disambiguates
        when multiple VMs match (e.g., AKS workloads also create control-plane VMs).
        Uses three methods to identify the real ARB VM:
        1. Cluster group: ARB VM belongs to the '<clusterName>-arcbridge' cluster group.
           The cluster group name reliably contains 'arcbridge' even though the VM name does not.
        2. MOC kubeconfig IP: Matches the API server IP from the ARB kubeconfig to VM network adapters.
           Kubeconfigs under paths containing 'arcbridge' are preferred over AKS kubeconfigs.
        3. ARB hex-ID name pattern: matches '<hex>-control-plan[hex/random]-<hex>' VM names.
           Two real-world variants are seen in the field — '<hex>-control-plane-0-<hex>' (older
           clusters) and '<hex>-control-plan<5-char-suffix>-<hex>' (newer clusters, e.g. LH-21).
           Both are covered. AKS control-plane VMs use non-hex prefixes so this still excludes them.
        Falls back to returning all matches if disambiguation fails.
    .OUTPUTS
        Array of Hyper-V VM objects, or empty array if none found on this node.
    #>

    [CmdletBinding()]
    param ()

    $vms = @(Get-VM -Name '*control-plan*' -ErrorAction Ignore)

    if ($vms.Count -le 1) {
        return $vms
    }

    # Multiple VMs matched — AKS workloads can create additional control-plane VMs.
    Write-Verbose "[$env:COMPUTERNAME][Get-ArbControlPlaneVMs] Found $($vms.Count) VMs matching '*control-plan*', disambiguating ARB VM..."

    # Method 1: Cross-reference with the ARB failover cluster group (<clusterName>-arcbridge)
    # The cluster group name reliably contains 'arcbridge'; the VM name itself does not.
    try {
        $clusterName = Get-AzsSupportEceManagementClusterName -ErrorAction Stop
        $arbGroupName = "$clusterName-arcbridge"
        $arbGroup = Get-ClusterGroup -Name $arbGroupName -ErrorAction Ignore
        if ($arbGroup) {
            $arbGroupResources = @(Get-ClusterResource -InputObject $arbGroup -ErrorAction Ignore |
                Where-Object { $_.ResourceType -eq 'Virtual Machine' })
            if ($arbGroupResources.Count -gt 0) {
                $arbResourceNames = @($arbGroupResources | ForEach-Object { $_.Name })
                # Cluster resource names for VMs are typically 'Virtual Machine <VMName>'
                $matched = @($vms | Where-Object {
                    $vmName = $_.Name
                    $arbResourceNames -contains $vmName -or $arbResourceNames -contains "Virtual Machine $vmName"
                })
                if ($matched.Count -gt 0) {
                    Write-Verbose "[$env:COMPUTERNAME][Get-ArbControlPlaneVMs] Narrowed to $($matched.Count) VM(s) by cluster group '$arbGroupName'"
                    return $matched
                }
            }
        }
    }
    catch {
        Write-Warning "[$env:COMPUTERNAME][Get-ArbControlPlaneVMs] Cluster group cross-reference skipped: $_"
    }

    # Method 2: Match VM network adapter IPs against the ARB kubeconfig API server IP
    # Prefer kubeconfigs whose path contains 'arcbridge' to avoid picking up AKS kubeconfigs.
    $arbIp = $null
    $mocCfg = Get-MocConfigCached -CallerName 'Get-ArbControlPlaneVMs'
    if ($mocCfg -and $mocCfg.WorkingDir -and (Test-Path $mocCfg.WorkingDir)) {
        $kubeconfigs = @(Get-ChildItem -Path $mocCfg.WorkingDir -Filter 'kubeconfig' -Recurse -Depth 10 -ErrorAction Ignore)
        # Prefer kubeconfigs under arcbridge paths
        $arcbridgeKubeconfigs = @($kubeconfigs | Where-Object { $_.FullName -like '*arcbridge*' })
        $orderedKubeconfigs = if ($arcbridgeKubeconfigs.Count -gt 0) { $arcbridgeKubeconfigs } else { $kubeconfigs }
        foreach ($kc in $orderedKubeconfigs) {
            $content = Get-Content -Path $kc.FullName -Raw -ErrorAction Ignore
            if ($content -match 'server:\s*https?://([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+):6443') {
                $arbIp = $matches[1]
                break
            }
        }
    }

    if ($arbIp) {
        $matched = @($vms | Where-Object {
            $vmIps = @(
                $_ | Get-VMNetworkAdapter -ErrorAction Ignore |
                ForEach-Object { $_.IPAddresses } |
                Where-Object { $_ -match '^\d+\.' }
            )
            $vmIps -contains $arbIp
        })
        if ($matched.Count -gt 0) {
            Write-Verbose "[$env:COMPUTERNAME][Get-ArbControlPlaneVMs] Narrowed to $($matched.Count) VM(s) by MOC kubeconfig IP ($arbIp)"
            return $matched
        }
    }

    # ------------------------------------------------------------------------------------------
    # Method 3: ARB-vs-AKS disambiguation by VM name regex — READ BEFORE MODIFYING
    # ------------------------------------------------------------------------------------------
    # The regex below matches ONLY the Arc Resource Bridge (ARB) control-plane VM.
    # It DELIBERATELY EXCLUDES AKS workload-cluster control-plane VMs (which can co-exist).
    #
    # Discriminator: the leading prefix before '-control-plan' must be ALL hex chars [0-9a-f].
    # ARB VM prefix is a derived Azure resource identifier — all hex, typically ~45 chars:
    # caa5017c65b71e53681da3c40ae39f0807ad6c3f216b0-control-planzzq2l-92b1f66d (newer)
    # 013bc87fb2959d61230552d6d19dc6c9e7483f83cd66-control-plane-0-3e9345d2 (older)
    # AKS workload-cluster control-plane VM prefix contains non-hex letters (g–z), e.g.
    # 0002akscls001-control-plane-... ('k','s','c','l' are not hex → no match)
    #
    # If you are looking for AKS control-plane VMs you need a DIFFERENT regex/lookup —
    # this one will silently skip them.
    # ------------------------------------------------------------------------------------------
    $matched = @($vms | Where-Object { $_.Name -imatch '^[0-9a-f]+-control-plan[a-z0-9-]+-[0-9a-f]+$' })
    if ($matched.Count -gt 0) {
        Write-Verbose "[$env:COMPUTERNAME][Get-ArbControlPlaneVMs] Narrowed to $($matched.Count) VM(s) by ARB hex-ID name pattern"
        return $matched
    }

    Write-Warning "[$env:COMPUTERNAME][Get-ArbControlPlaneVMs] Could not disambiguate $($vms.Count) control-plane VMs. Returning all matches."
    return $vms
}

function Get-ArbControlPlaneTargets {
    <#
    .SYNOPSIS
        Discovers ARB control-plane VM IPv4 addresses.
    .DESCRIPTION
        Uses two methods to find ARB control-plane VM IPs:
        1. Local Hyper-V (Get-VM) for VMs matching '*control-plan*' on this node.
        2. Parses kubeconfig files in the MOC working directory and ClusterStorage
           for the Kubernetes API server IP (port 6443).
        Method 2 uses Get-MocConfigCached to locate the MOC working directory.
    .PARAMETER CallerName
        Label used in diagnostic messages.
    .OUTPUTS
        Array of unique IPv4 address strings, or empty array if none found.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$CallerName = 'MocArb'
    )

    $arbTargets = @()

    # Method 1: Local Get-VM for ARB control-plane VMs on this node
    $arbVMs = Get-ArbControlPlaneVMs
    if ($arbVMs) {
        $arbTargets = @(
            $arbVMs |
            Get-VMNetworkAdapter -ErrorAction Ignore |
            ForEach-Object { $_.IPAddresses } |
            Where-Object { $_ } |
            Where-Object { $_ -match '^\d+\.' }
        )
    }

    # Method 2: Parse kubeconfig files for API server IP
    if ($arbTargets.Count -eq 0) {
        $searchPaths = @()
        $mocCfg = Get-MocConfigCached -CallerName $CallerName
        if ($mocCfg.WorkingDir) { $searchPaths += $mocCfg.WorkingDir }
        $searchPaths += 'C:\ClusterStorage'

        foreach ($searchPath in $searchPaths) {
            if (-not (Test-Path $searchPath)) { continue }
            $kubeconfigs = @(Get-ChildItem -Path $searchPath -Filter 'kubeconfig' -Recurse -Depth 10 -ErrorAction Ignore)

            # On clusters with AKS workloads, multiple kubeconfigs exist (ARB + AKS target clusters).
            # Prefer kubeconfigs whose path contains 'arcbridge' to avoid testing AKS endpoints.
            $arcbridgeKubeconfigs = @($kubeconfigs | Where-Object { $_.FullName -like '*arcbridge*' })
            $orderedKubeconfigs = if ($arcbridgeKubeconfigs.Count -gt 0) { $arcbridgeKubeconfigs } else { $kubeconfigs }

            foreach ($kc in $orderedKubeconfigs) {
                $content = Get-Content -Path $kc.FullName -Raw -ErrorAction Ignore
                if ($content -match 'server:\s*https?://([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+):6443') {
                    $arbTargets += $matches[1]
                }
            }
            $arbTargets = @($arbTargets | Select-Object -Unique)
            if ($arbTargets.Count -gt 0) { break }
        }
    }

    return $arbTargets
}

function Get-ArbKubeconfigs {
    <#
    .SYNOPSIS
        Finds ARB kubeconfig files on the local node.
    .DESCRIPTION
        Searches the MOC working directory and ClusterStorage for kubeconfig files
        that contain a Kubernetes API server endpoint (port 6443).
    .PARAMETER CallerName
        Label used in diagnostic messages.
    .OUTPUTS
        Array of FileInfo objects for matching kubeconfig files.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$CallerName = 'MocArb'
    )

    $searchPaths = @()
    $mocCfg = Get-MocConfigCached -CallerName $CallerName
    if ($mocCfg.WorkingDir) { $searchPaths += $mocCfg.WorkingDir }
    $searchPaths += 'C:\ClusterStorage'

    $found = @()
    foreach ($searchPath in $searchPaths) {
        if (-not (Test-Path $searchPath)) { continue }
        $kubeconfigs = @(Get-ChildItem -Path $searchPath -Filter 'kubeconfig' -Recurse -Depth 10 -ErrorAction Ignore)
        foreach ($kc in $kubeconfigs) {
            $content = Get-Content -Path $kc.FullName -Raw -ErrorAction Ignore
            if ($content -match 'server:\s*https?://[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:6443') {
                $found += $kc
            }
        }
        if ($found.Count -gt 0) { break }
    }

    return $found
}

function Get-EffectiveVlanId {
    <#
    .SYNOPSIS
        Resolves the effective VLAN ID applied to a Hyper-V virtual network adapter.
    .DESCRIPTION
        A Hyper-V vNIC can carry its VLAN in one of two places depending on how the
        port is programmed:
          - Access mode: the VLAN is in 'AccessVlanId' (Get-VMNetworkAdapterVlan) and
            the isolation 'DefaultIsolationID' reads 0.
          - VLAN isolation mode: the VLAN is in 'DefaultIsolationID'
            (Get-VMNetworkAdapterIsolation) and 'AccessVlanId' reads 0. SDN / ARC-SDN
            managed ports (including the ARB control-plane VM NIC) run in this mode.
        Reading only one source produces a false mismatch when the port uses the other.
        This helper applies the same precedence the virtual switch applies, so an
        access-mode port and an isolation-mode port carrying the same VLAN resolve to
        the same effective value.
    .PARAMETER VlanInfo
        The object returned by Get-VMNetworkAdapterVlan for the adapter. Optional.
    .PARAMETER IsolationInfo
        The object returned by Get-VMNetworkAdapterIsolation for the adapter. Optional.
    .OUTPUTS
        PSCustomObject with EffectiveVlanId, Source, and the raw diagnostic fields
        (OperationMode, AccessVlanId, IsolationMode, DefaultIsolationID). EffectiveVlanId
        is an int when the VLAN can be resolved, or $null with Source 'Unknown' when the
        adapter VLAN could not be determined (no usable isolation data and AccessVlanId 0).
    #>

    [CmdletBinding()]
    param (
        [Parameter()]
        [object] $VlanInfo,

        [Parameter()]
        [object] $IsolationInfo
    )

    $operationMode = $null
    $accessVlanId = $null
    $isolationMode = $null
    $defaultIsolationId = $null

    if ($null -ne $VlanInfo) {
        $operationMode = $VlanInfo.OperationMode
        $accessVlanId = $VlanInfo.AccessVlanId
    }
    if ($null -ne $IsolationInfo) {
        $isolationMode = $IsolationInfo.IsolationMode
        $defaultIsolationId = $IsolationInfo.DefaultIsolationID
    }

    # Precedence: a port in VLAN isolation mode carries its VLAN in DefaultIsolationID
    # (AccessVlanId reads 0 there). Otherwise an access-mode port carries it in
    # AccessVlanId. If neither is set and isolation data was readable the port is
    # genuinely untagged (0). If isolation data could NOT be read, an AccessVlanId of 0
    # is ambiguous (it cannot distinguish an untagged port from a VLAN-isolation port
    # whose tag lives in DefaultIsolationID), so the effective VLAN is left unresolved
    # (null) and the caller keeps this adapter out of the drift comparison.
    if (($null -ne $isolationMode) -and ("$isolationMode" -eq 'Vlan') -and ($null -ne $defaultIsolationId) -and ([int]$defaultIsolationId -gt 0)) {
        $effectiveVlanId = [int]$defaultIsolationId
        $source = 'DefaultIsolationID'
    }
    elseif (($null -ne $accessVlanId) -and ([int]$accessVlanId -gt 0)) {
        $effectiveVlanId = [int]$accessVlanId
        $source = 'AccessVlanId'
    }
    elseif ($null -ne $IsolationInfo) {
        $effectiveVlanId = 0
        $source = 'Untagged'
    }
    else {
        $effectiveVlanId = $null
        $source = 'Unknown'
    }

    return [PSCustomObject]@{
        EffectiveVlanId    = $effectiveVlanId
        Source             = $source
        OperationMode      = $operationMode
        AccessVlanId       = $accessVlanId
        IsolationMode      = $isolationMode
        DefaultIsolationID = $defaultIsolationId
    }
}

function Get-CimReferenceKeyValue {
    <#
    .SYNOPSIS
        Extracts a key property value from a CIM reference-typed property.
    .DESCRIPTION
        Reference-typed properties on a CimInstance (for example the 'Parent' and
        'HostResource' properties of Msvm_EthernetPortAllocationSettingData) may be
        surfaced either as a Microsoft.Management.Infrastructure.CimInstance whose key
        properties are populated, or as a WMI object-path string of the form
        '...InstanceID="Microsoft:GUID\\GUID"...'. This helper returns the requested key
        value regardless of which representation is used, so callers do not have to
        branch on the shape of the reference.
    .PARAMETER Reference
        The reference-typed property value (CimInstance or object-path string).
    .PARAMETER KeyName
        The name of the key property to extract (for example 'InstanceID' or 'Name').
    .OUTPUTS
        The string value of the requested key, or $null when it cannot be resolved.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param (
        [Parameter()]
        [object] $Reference,

        [Parameter(Mandatory = $true)]
        [string] $KeyName
    )

    if ($null -eq $Reference) {
        return $null
    }

    if ($Reference -is [Microsoft.Management.Infrastructure.CimInstance]) {
        $property = $Reference.CimInstanceProperties[$KeyName]
        if ($null -ne $property) {
            return [string]$property.Value
        }
        return $null
    }

    # Fall back to parsing an object-path string such as ...KeyName="value"...
    # Anchor the key name on a word boundary so it cannot match as a substring of a
    # different key. For example, Msvm_VirtualEthernetSwitch is a two-key class and its
    # real HostResource reference is:
    # Msvm_VirtualEthernetSwitch.CreationClassName="Msvm_VirtualEthernetSwitch",Name="<switch-guid>"
    # An unanchored 'Name="([^"]*)"' would match inside CreationClassName and return the
    # class name instead of the GUID; the '\b' anchor forces a match on the standalone key.
    $match = [regex]::Match([string]$Reference, '\b' + [regex]::Escape($KeyName) + '="([^"]*)"')
    if ($match.Success) {
        # Backslashes inside a WMI object-path key value are escaped (doubled). The real
        # Parent reference emitted by Hyper-V is, for example,
        # Msvm_SyntheticEthernetPortSettingData.InstanceID="Microsoft:<guid>\\<portGuid>"
        # Unescape the doubled backslash so the returned value matches the single-backslash
        # form the referenced instance reports through its own InstanceID key property
        # (otherwise the correlating hashtable lookup in Get-VMNetworkAdapterFromCim misses
        # and every adapter is silently skipped).
        return $match.Groups[1].Value -replace '\\\\', '\'
    }

    return $null
}

function Get-VMNetworkAdapterFromCim {
    <#
    .SYNOPSIS
        Collects Hyper-V VM network adapters using CIM cmdlets instead of Get-VMNetworkAdapter.
    .DESCRIPTION
        Get-VMNetworkAdapter is expensive on hosts with many VMs because it performs a large
        number of per-adapter WMI association traversals. This helper issues a small, fixed
        number of bulk Get-CimInstance queries against the root\virtualization\v2 namespace and
        correlates the results in memory, which scales far better on dense hosts.
 
        Only adapters that are connected to a virtual switch are returned (the connection is
        represented by Msvm_EthernetPortAllocationSettingData). Disconnected adapters have no
        switch association and are therefore not relevant to switch-scoped checks.
 
        The returned objects mirror the subset of Get-VMNetworkAdapter properties that the
        switch insight rules consume, so those rules do not need to change.
    .OUTPUTS
        PSCustomObject collection, each with: Name, VMName, IsManagementOs, SwitchName,
        SwitchId, MacAddress, and MacAddressSpoofing ('On' or 'Off').
    #>

    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSObject[]])]
    param ()

    $namespace = 'root\virtualization\v2'
    $cimParams = @{ Namespace = $namespace; ErrorAction = 'Stop' }

    try {
        # Virtual switches: correlate by Name (the switch GUID, which matches Get-VMSwitch.Id).
        $switchByGuid = @{}
        foreach ($vSwitch in @(Get-CimInstance @cimParams -ClassName 'Msvm_VirtualEthernetSwitch')) {
            if (-not [string]::IsNullOrEmpty($vSwitch.Name)) {
                $switchByGuid[$vSwitch.Name] = $vSwitch
            }
        }

        # The host ("Hosting Computer System") owns the management OS (host) vNICs; any adapter
        # whose owning system GUID equals the host GUID is a management OS adapter.
        $hostSystemGuid = $null
        $vmNameByGuid = @{}
        foreach ($system in @(Get-CimInstance @cimParams -ClassName 'Msvm_ComputerSystem')) {
            if (-not [string]::IsNullOrEmpty($system.Name)) {
                $vmNameByGuid[$system.Name] = $system.ElementName
            }
            if ($system.Caption -ieq 'Hosting Computer System') {
                $hostSystemGuid = $system.Name
            }
        }

        # Port setting data describes each adapter (name, MAC). Both synthetic and emulated NICs.
        $portByInstanceId = @{}
        foreach ($portClass in @('Msvm_SyntheticEthernetPortSettingData', 'Msvm_EmulatedEthernetPortSettingData')) {
            foreach ($port in @(Get-CimInstance @cimParams -ClassName $portClass)) {
                if (-not [string]::IsNullOrEmpty($port.InstanceID)) {
                    $portByInstanceId[$port.InstanceID] = $port
                }
            }
        }

        # Security setting data carries AllowMacSpoofing. Its InstanceID is the owning connection's
        # InstanceID plus a feature suffix, so index by the connection prefix for correlation.
        $securityByConnectionId = @{}
        foreach ($security in @(Get-CimInstance @cimParams -ClassName 'Msvm_EthernetSwitchPortSecuritySettingData')) {
            if ([string]::IsNullOrEmpty($security.InstanceID)) {
                continue
            }
            # InstanceID form: '<connection InstanceID>\<featureGuid>'. Strip the last segment.
            $connectionId = $security.InstanceID -replace '\\[^\\]*$', ''
            if (-not [string]::IsNullOrEmpty($connectionId)) {
                $securityByConnectionId[$connectionId] = $security
            }
        }

        $adapters = [System.Collections.Generic.List[object]]::new()

        # Each connection (allocation) ties an adapter port to a virtual switch.
        foreach ($connection in @(Get-CimInstance @cimParams -ClassName 'Msvm_EthernetPortAllocationSettingData')) {
            # Resolve the switch this connection targets from its HostResource references.
            $vSwitch = $null
            foreach ($hostResource in @($connection.HostResource)) {
                $switchGuid = Get-CimReferenceKeyValue -Reference $hostResource -KeyName 'Name'
                if (-not [string]::IsNullOrEmpty($switchGuid) -and $switchByGuid.ContainsKey($switchGuid)) {
                    $vSwitch = $switchByGuid[$switchGuid]
                    break
                }
            }

            # Skip connections that are not attached to a known virtual switch.
            if ($null -eq $vSwitch) {
                continue
            }

            # Resolve the adapter port backing this connection.
            $portInstanceId = Get-CimReferenceKeyValue -Reference $connection.Parent -KeyName 'InstanceID'
            if ([string]::IsNullOrEmpty($portInstanceId) -or -not $portByInstanceId.ContainsKey($portInstanceId)) {
                continue
            }
            $port = $portByInstanceId[$portInstanceId]

            # MAC spoofing state comes from the security feature setting on this connection.
            $macAddressSpoofing = 'Off'
            if ($securityByConnectionId.ContainsKey($connection.InstanceID)) {
                $security = $securityByConnectionId[$connection.InstanceID]
                if ($security.AllowMacSpoofing) {
                    $macAddressSpoofing = 'On'
                }
            }

            # The owning system GUID is the first path segment of the port InstanceID
            # ('Microsoft:<systemGuid>\<portGuid>').
            $systemGuid = $null
            $instanceCore = $portInstanceId -replace '^Microsoft:', ''
            if ($instanceCore.Contains('\')) {
                $systemGuid = $instanceCore.Substring(0, $instanceCore.IndexOf('\'))
            }

            $isManagementOs = (-not [string]::IsNullOrEmpty($hostSystemGuid)) -and ($systemGuid -eq $hostSystemGuid)
            $vmName = if ($isManagementOs) { $null } elseif ($null -ne $systemGuid -and $vmNameByGuid.ContainsKey($systemGuid)) { $vmNameByGuid[$systemGuid] } else { $null }

            $adapters.Add([PSCustomObject]@{
                Name               = $port.ElementName
                VMName             = $vmName
                IsManagementOs     = $isManagementOs
                SwitchName         = $vSwitch.ElementName
                SwitchId           = $vSwitch.Name
                MacAddress         = $port.Address
                MacAddressSpoofing = $macAddressSpoofing
            })
        }

        return $adapters.ToArray()
    }
    catch {
        # Surface CIM failures as a non-terminating error so callers using
        # -ErrorAction SilentlyContinue gracefully skip (returning no adapters)
        # instead of the whole analyzer going UNKNOWN on the terminating error.
        Write-Error -ErrorRecord $_
        return @()
    }
}

# SIG # Begin signature block
# MIInUAYJKoZIhvcNAQcCoIInQTCCJz0CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCD+uE0uUehsCc5g
# WNOAfkUHpGfSJgX2smjTkuXNOEMna6CCDMkwggYEMIID7KADAgECAhMzAAACHPrN
# xZvoL37EAAAAAAIcMA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNVBAYTAlVTMR4wHAYD
# VQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBD
# b2RlIFNpZ25pbmcgUENBIDIwMjQwHhcNMjYwNDE2MTg1OTQxWhcNMjcwNDE1MTg1
# OTQxWjB0MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UE
# BxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMR4wHAYD
# VQQDExVNaWNyb3NvZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUAA4IB
# DwAwggEKAoIBAQDVsZfgOKmM31HPfoWOoNEiw0SlCiIxUMC0I9NMWbucKOw/e9lP
# oAoehQVu6SG65V4EPzrYsnBnFPNoi4/HoOdjhz1qkrEt4I6tEcxXU6oOeY9zGveC
# /3iBeuhLYxM3M/PkcUoebF+Nednm8OkdSPoDu8imViHPQq/8CQUu0WRR4rE+dMRf
# rpVqfmNi2qWCX94T4MsepijGVkwE//tJg0ryAiYdHT34LSnlG/RSBZmQRGWZ5g8j
# qnKjRParSqMft1gvjuUTVgtWNZfgcLFSK5Wa0myrq8OPcgTGGsRgun+tnSS+IxDT
# xVsAPH1OzvPjwomguByhUe/OcvUN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