Private/Inventory.ps1

# Inventory: scope tags, role assignments and every taggable Intune object, normalised into one row shape.

function Get-STMTypeRegistry {
    if (-not $script:STM.Registry) {
        $path = Join-Path $script:STM.ModuleRoot 'Config/TypeRegistry.json'
        $script:STM.Registry = (Get-Content -LiteralPath $path -Raw | ConvertFrom-Json).types
    }
    return $script:STM.Registry
}

function Get-STMTypeDef {
    param([Parameter(Mandatory)][string]$Key)
    $t = Get-STMTypeRegistry | Where-Object { $_.key -eq $Key } | Select-Object -First 1
    if (-not $t) { throw "Unknown object type '$Key'. Known types: $((Get-STMTypeRegistry).key -join ', ')" }
    return $t
}

function Get-STMProp {
    param($Object, [string]$Name)
    if ($null -eq $Object) { return $null }
    if ($Object -is [System.Collections.IDictionary]) { if ($Object.Contains($Name)) { return $Object[$Name] } else { return $null } }
    $p = $Object.PSObject.Properties[$Name]
    if ($p) { return $p.Value }
    return $null
}

function Test-STMHasProp {
    param($Object, [string]$Name)
    if ($Object -is [System.Collections.IDictionary]) { return $Object.Contains($Name) }
    return [bool]$Object.PSObject.Properties[$Name]
}

function ConvertTo-STMPlatform {
    param([string]$ODataType, $Value)
    if ($Value) {
        $v = (@($Value) -join ',')
        switch -Regex ($v) {
            '(?i)^ios|iOS' { return 'iOS/iPadOS' }
            '(?i)macos' { return 'macOS' }
            '(?i)android|aosp' { return 'Android' }
            '(?i)windows|win' { return 'Windows' }
            '(?i)linux' { return 'Linux' }
        }
        return $v
    }
    if (-not $ODataType) { return '' }
    $t = $ODataType.ToLowerInvariant()
    if ($t -match 'macos') { return 'macOS' }
    if ($t -match '\.ios|ipad') { return 'iOS/iPadOS' }
    if ($t -match 'android|aosp') { return 'Android' }
    if ($t -match 'windows|win32|win10|office|microsoftstore|edge|winget|webapp') {
        if ($t -match 'webapp') { return 'Web' }
        return 'Windows'
    }
    if ($t -match 'linux') { return 'Linux' }
    return ''
}

function ConvertTo-STMIsoDate {
    # PowerShell 7 turns ISO dates in JSON into DateTime; keep them as ISO 8601 UTC strings everywhere.
    param($Value)
    if ($null -eq $Value) { return '' }
    if ($Value -is [datetime]) { return $Value.ToUniversalTime().ToString('o') }
    if ($Value -is [datetimeoffset]) { return $Value.UtcDateTime.ToString('o') }
    return [string]$Value
}

$script:STMPlatformCache = [System.Collections.Generic.Dictionary[string, string]]::new()

function ConvertTo-STMRow {
    # Hot path (runs once per object; 170k+ times for devices), so property reads are inlined and no pipelines are used.
    param([Parameter(Mandatory)]$TypeDef, [Parameter(Mandatory)]$Object)
    if ($Object -is [System.Collections.IDictionary]) { $Object = [pscustomobject]$Object }
    $props = $Object.PSObject.Properties
    $p = $props['@odata.type']; $odata = if ($p) { [string]$p.Value } else { '' }
    $p = $props['id']; $id = if ($p) { [string]$p.Value } else { '' }
    $p = $props[$TypeDef.nameProperty]; $name = if ($p) { [string]$p.Value } else { '' }
    if (-not $name) { foreach ($n in 'displayName', 'name', 'deviceName', 'tokenName', 'profileName') { $p = $props[$n]; if ($p -and $p.Value) { $name = [string]$p.Value; break } } }
    if (-not $name) { $name = "(no name) $id" }
    $defProps = $TypeDef.PSObject.Properties
    $tagProp = if ($defProps['tagProperty']) { $TypeDef.tagProperty } else { 'roleScopeTagIds' }
    $p = $props[$tagProp]
    $hasTags = [bool]$p
    $tags = [string[]]@()
    if ($p -and $null -ne $p.Value) {
        $set = [System.Collections.Generic.SortedSet[string]]::new([System.StringComparer]::Ordinal)
        foreach ($t in @($p.Value)) { $v = [string]$t; if ($v -ne '') { [void]$set.Add($v) } }
        $tags = [string[]]@($set)
    }
    $platform = ''
    if ($defProps['fixedPlatform']) { $platform = $TypeDef.fixedPlatform }
    else {
        $pv = $null
        if ($defProps['platformProperty']) { $pp = $props[$TypeDef.platformProperty]; if ($pp) { $pv = $pp.Value } }
        $ck = "$odata|$(@($pv) -join ',')"
        if (-not $script:STMPlatformCache.TryGetValue($ck, [ref]$platform)) {
            $platform = ConvertTo-STMPlatform -ODataType $odata -Value $pv
            $script:STMPlatformCache[$ck] = $platform
        }
    }
    $supported = $true; $note = ''
    if ($defProps['excludeWhen']) {
        $ex = $TypeDef.excludeWhen; $pe = $props[$ex.property]
        if ($pe -and $pe.Value -eq $ex.equals) { $supported = $false; $note = $ex.reason }
    }
    if ($supported -and $defProps['warnWhen']) {
        $w = $TypeDef.warnWhen; $pw = $props[$w.property]
        if ($pw -and $pw.Value -eq $w.equals) { $note = $w.reason }
    }
    if ($TypeDef.key -eq 'MobileApp' -and $odata -match '(?i)vpp') { $note = "Inherits the VPP token's scope tags; tag the VPP token instead" }
    $extra = $null
    if ($TypeDef.key -eq 'ManagedDevice') {
        $p = $props['lastSyncDateTime']; $modified = ConvertTo-STMIsoDate $(if ($p) { $p.Value } else { $null })
        $vals = @{}
        foreach ($n in 'serialNumber', 'userPrincipalName', 'operatingSystem', 'osVersion', 'managedDeviceOwnerType', 'managementAgent') {
            $q = $props[$n]; $vals[$n] = if ($q -and $null -ne $q.Value) { [string]$q.Value } else { '' }
        }
        $extra = [ordered]@{
            serial = $vals.serialNumber; upn = $vals.userPrincipalName; os = ($vals.operatingSystem + ' ' + $vals.osVersion).Trim()
            owner = $vals.managedDeviceOwnerType; agent = $vals.managementAgent
        }
    }
    else { $p = $props['lastModifiedDateTime']; $modified = ConvertTo-STMIsoDate $(if ($p) { $p.Value } else { $null }) }
    [pscustomobject][ordered]@{
        Key = "$($TypeDef.key)|$id"
        Type = $TypeDef.key
        TypeLabel = $TypeDef.label
        Category = $TypeDef.category
        Id = $id
        Name = $name
        Platform = $platform
        ODataType = $odata
        TagIds = $tags
        TagsKnown = $hasTags
        Modified = $modified
        Supported = $supported
        Note = $note
        Status = $TypeDef.status
        Extra = $extra
    }
}

function Update-STMScopeTags {
    # Loads scope tags with their group assignments (groups on a tag auto-apply it to devices).
    $tags = Get-STMCollection -Uri 'deviceManagement/roleScopeTags'
    $list = [System.Collections.Generic.List[object]]::new()
    $reqs = @(foreach ($t in $tags) { @{ id = [string]$t.id; method = 'GET'; url = "/deviceManagement/roleScopeTags/$($t.id)/assignments"; body = $null } })
    $assign = @{}
    if ($reqs.Count) { $assign = Invoke-STMBatch -Requests $reqs }
    foreach ($t in $tags) {
        $groups = @()
        $a = $assign[[string]$t.id]
        if ($a -and $a.status -lt 300 -and $a.body) {
            $groups = @(@($a.body.value) | ForEach-Object { [string](Get-STMProp $_.target 'groupId') } | Where-Object { $_ })
        }
        $list.Add([pscustomobject][ordered]@{
            Id = [string]$t.id
            Name = if ([string]$t.id -eq '0' -and -not $t.displayName) { 'Default' } else { [string]$t.displayName }
            Description = [string](Get-STMProp $t 'description')
            IsBuiltIn = [bool](Get-STMProp $t 'isBuiltIn') -or ([string]$t.id -eq '0')
            AssignedGroupIds = $groups
        })
    }
    $script:STM.Tags = $list
    $script:STM.TagsLoadedAt = [DateTime]::UtcNow
    return $list
}

function Update-STMRoleAssignments {
    # Intune RBAC: role definitions -> their assignments -> each assignment's members, scope groups and scope tags.
    $defs = Get-STMCollection -Uri 'deviceManagement/roleDefinitions'
    $reqs = @(foreach ($d in $defs) { @{ id = [string]$d.id; method = 'GET'; url = "/deviceManagement/roleDefinitions/$($d.id)/roleAssignments"; body = $null } })
    $byDef = @{}
    if ($reqs.Count) { $byDef = Invoke-STMBatch -Requests $reqs }
    $assignmentRefs = [System.Collections.Generic.List[object]]::new()
    foreach ($d in $defs) {
        $r = $byDef[[string]$d.id]
        if ($r -and $r.status -lt 300 -and $r.body) {
            foreach ($a in @($r.body.value)) { $assignmentRefs.Add([pscustomobject]@{ AssignmentId = [string]$a.id; Def = $d }) }
        }
    }
    $full = @{}
    if ($assignmentRefs.Count) {
        $full = Invoke-STMBatch -Requests @(foreach ($ar in $assignmentRefs) { @{ id = $ar.AssignmentId; method = 'GET'; url = "/deviceManagement/roleAssignments/$($ar.AssignmentId)"; body = $null } })
    }
    $list = [System.Collections.Generic.List[object]]::new()
    foreach ($ar in $assignmentRefs) {
        $a = $full[$ar.AssignmentId]
        $o = if ($a -and $a.status -lt 300) { $a.body } else { $null }
        $list.Add([pscustomobject][ordered]@{
            Id = $ar.AssignmentId
            Name = [string](Get-STMProp $o 'displayName')
            RoleName = [string]$ar.Def.displayName
            RoleIsBuiltIn = [bool](Get-STMProp $ar.Def 'isBuiltIn')
            MemberGroupIds = @(Get-STMProp $o 'members' | Where-Object { $_ })
            ScopeGroupIds = @(@(Get-STMProp $o 'scopeMembers') + @(Get-STMProp $o 'resourceScopes') | Where-Object { $_ } | Sort-Object -Unique)
            ScopeType = [string](Get-STMProp $o 'scopeType')
            TagIds = @(@(Get-STMProp $o 'roleScopeTagIds') | Where-Object { "$_" -ne '' } | ForEach-Object { [string]$_ })
            ReadError = if ($o) { '' } else { [string]$a.error }
        })
    }
    $script:STM.RoleAssignments = $list
    $script:STM.RoleAssignmentsLoadedAt = [DateTime]::UtcNow
    $gids = @($list | ForEach-Object { @($_.MemberGroupIds) + @($_.ScopeGroupIds) }) + @($script:STM.Tags | ForEach-Object { @($_.AssignedGroupIds) })
    Resolve-STMGroupNames -GroupIds $gids
    return $list
}

function Resolve-STMGroupNames {
    # Optional: needs Group.Read.All or Directory.Read.All. Without it the UI shows group ids.
    param([string[]]$GroupIds)
    $ids = @($GroupIds | Where-Object { $_ -and -not $script:STM.GroupNames.ContainsKey($_) } | Sort-Object -Unique)
    if (-not $ids.Count -or -not $script:STM.Settings.ResolveGroupNames) { return }
    for ($i = 0; $i -lt $ids.Count; $i += 1000) {
        $chunk = @($ids[$i..([math]::Min($i + 999, $ids.Count - 1))])
        try {
            $r = Invoke-STMGraph -Method POST -Uri 'https://graph.microsoft.com/v1.0/directoryObjects/getByIds' -Body @{ ids = $chunk; types = @('group') }
            foreach ($g in @($r.value)) { $script:STM.GroupNames[[string]$g.id] = [string]$g.displayName }
            $script:STM.GroupNameStatus = 'Resolved'
        }
        catch { $script:STM.GroupNameStatus = 'Group names need Group.Read.All (optional); showing ids'; return }
    }
}

function Update-STMTypeInventory {
    # Loads one object type. Optional endpoints that do not exist in a tenant are reported, not fatal.
    param([Parameter(Mandatory)][string]$TypeKey)
    $def = Get-STMTypeDef -Key $TypeKey
    $status = [ordered]@{ Type = $TypeKey; Label = $def.label; Category = $def.category; Count = 0; State = 'Loading'; Error = ''; LoadedAt = $null; SelectFallback = $false; TagsMissing = 0 }
    $base = $def.path
    $uri = $base
    $hasSelect = $def.PSObject.Properties['select'] -and $def.select
    if ($hasSelect) { $uri = "$base`?`$select=$($def.select)" }
    $objects = $null
    try { $objects = Get-STMCollection -Uri $uri }
    catch {
        $kind = $_.Exception.Data['Kind']
        if ($hasSelect -and $kind -eq 'BadRequest') {
            $status.SelectFallback = $true
            try { $objects = Get-STMCollection -Uri $base } catch { $objects = $null; $status.Error = $_.Exception.Message }
        }
        else { $status.Error = $_.Exception.Message }
        if ($null -eq $objects) {
            $optional = $def.PSObject.Properties['optional'] -and $def.optional
            $appRefused = $optional -and $script:STM.AppOnly -and $_.Exception.Data['Kind'] -in 'NotSignedIn', 'Forbidden' -and (($script:STM.TokenCheck -and $script:STM.TokenCheck.ok) -or ($script:STM.Tags -and @($script:STM.Tags).Count))
            $status.State = if ($optional -and $_.Exception.Data['Kind'] -in 'NotFound', 'BadRequest') { 'NotAvailable' } elseif ($appRefused) { 'AppSignInNotSupported' } elseif ($_.Exception.Data['Kind'] -eq 'Forbidden') { 'NoPermission' } else { 'Failed' }
            if ($status.State -eq 'Failed' -and -not $status.Error) { $status.Error = $_.Exception.Message }
            if ($status.State -eq 'AppSignInNotSupported') { $status.Error = 'This Intune area does not accept the app sign-in, though the others do. Sign in with your own account to include it.' }
            $script:STM.TypeStatus[$TypeKey] = [pscustomobject]$status
            return [pscustomobject]$status
        }
    }
    # Replace this type's rows atomically so a refresh never shows half old, half new.
    foreach ($k in @($script:STM.Inventory.Keys | Where-Object { $_.StartsWith("$TypeKey|") })) { $script:STM.Inventory.Remove($k) }
    foreach ($o in $objects) {
        $row = ConvertTo-STMRow -TypeDef $def -Object $o
        if (-not $row.TagsKnown) { $status.TagsMissing++ }
        $script:STM.Inventory[$row.Key] = $row
    }
    $status.Count = $objects.Count
    $status.State = 'Loaded'
    $status.LoadedAt = [DateTime]::UtcNow.ToString('o')
    $script:STM.TypeStatus[$TypeKey] = [pscustomobject]$status
    return [pscustomobject]$status
}

# ---- Devices stream in pages so 170k+ devices never block the UI. ----

function Start-STMDeviceLoad {
    param([string]$OperatingSystem, [string]$NameStartsWith)
    $def = Get-STMTypeDef -Key 'ManagedDevice'
    $filters = @()
    if ($OperatingSystem) { $filters += "operatingSystem eq '$($OperatingSystem.Replace("'", "''"))'" }
    if ($NameStartsWith) { $filters += "startswith(deviceName,'$($NameStartsWith.Replace("'", "''"))')" }
    $q = @("`$select=$($def.select)", "`$top=$($def.pageSize)")
    if ($filters) { $q += "`$filter=$([uri]::EscapeDataString($filters -join ' and '))" }
    foreach ($k in @($script:STM.Inventory.Keys | Where-Object { $_.StartsWith('ManagedDevice|') })) { $script:STM.Inventory.Remove($k) }
    $script:STM.DeviceLoad = [ordered]@{ Next = "$($def.path)?$($q -join '&')"; LastPage = @(); Loaded = 0; Done = $false; TagsMissing = 0; Filter = ($filters -join ' and '); SelectFallback = $false }
    $script:STM.TypeStatus['ManagedDevice'] = [pscustomobject]@{ Type = 'ManagedDevice'; Label = $def.label; Category = $def.category; Count = 0; State = 'Loading'; Error = ''; LoadedAt = $null; SelectFallback = $false; TagsMissing = 0 }
    return [pscustomobject]$script:STM.DeviceLoad
}

function Step-STMDeviceLoad {
    # Loads one page (up to 999 devices). Call until Done.
    $dl = $script:STM.DeviceLoad
    if (-not $dl -or $dl.Done) { return [pscustomobject]$dl }
    $dl.LastPage = @()
    $def = Get-STMTypeDef -Key 'ManagedDevice'
    try { $resp = Invoke-STMGraph -Method GET -Uri $dl.Next }
    catch {
        if ($_.Exception.Data['Kind'] -eq 'BadRequest' -and -not $dl.SelectFallback -and $dl.Next -match 'select=') {
            $dl.SelectFallback = $true
            $dl.Next = $dl.Next -replace '\$select=[^&]*&?', ''
            return [pscustomobject]$dl
        }
        $dl.Done = $true
        $script:STM.TypeStatus['ManagedDevice'].State = 'Failed'
        $script:STM.TypeStatus['ManagedDevice'].Error = $_.Exception.Message
        return [pscustomobject]$dl
    }
    $pageRows = [System.Collections.Generic.List[object]]::new()
    foreach ($o in @($resp.value)) {
        $row = ConvertTo-STMRow -TypeDef $def -Object $o
        if (-not $row.TagsKnown) { $dl.TagsMissing++ }
        $script:STM.Inventory[$row.Key] = $row
        $pageRows.Add($row)
        $dl.Loaded++
    }
    $dl.LastPage = $pageRows
    $dl.Next = if ($resp.PSObject.Properties['@odata.nextLink']) { [string]$resp.'@odata.nextLink' } else { $null }
    if (-not $dl.Next) {
        $dl.Done = $true
        $st = $script:STM.TypeStatus['ManagedDevice']
        $st.State = 'Loaded'; $st.LoadedAt = [DateTime]::UtcNow.ToString('o')
    }
    $st = $script:STM.TypeStatus['ManagedDevice']
    $st.Count = $dl.Loaded; $st.TagsMissing = $dl.TagsMissing; $st.SelectFallback = $dl.SelectFallback
    return [pscustomobject]$dl
}

function Update-STMDeviceTags {
    # Fallback when a device list does not return roleScopeTagIds: read tags per device (batched) for the given ids only.
    param([Parameter(Mandatory)][string[]]$DeviceIds)
    $def = Get-STMTypeDef -Key 'ManagedDevice'
    $res = Invoke-STMBatch -Requests @(foreach ($id in $DeviceIds) { @{ id = $id; method = 'GET'; url = "/deviceManagement/managedDevices/$id`?`$select=id,roleScopeTagIds"; body = $null } })
    $n = 0
    foreach ($id in $DeviceIds) {
        $r = $res[$id]; $key = "ManagedDevice|$id"
        if ($r -and $r.status -lt 300 -and $script:STM.Inventory.ContainsKey($key)) {
            $row = $script:STM.Inventory[$key]
            $row.TagIds = @(@($r.body.roleScopeTagIds) | ForEach-Object { [string]$_ } | Sort-Object -Unique)
            $row.TagsKnown = $true
            $n++
        }
    }
    return $n
}

function Get-STMLiveObject {
    # Reads current state of objects straight from Graph (used for CSV imports of objects not in the loaded inventory, and drift checks).
    param([Parameter(Mandatory)][object[]]$Refs)  # each @{ Type; Id }
    $reqs = @(foreach ($r in $Refs) {
        $def = Get-STMTypeDef -Key $r.Type
        $u = "/$($def.path)/$($r.Id)"
        # Devices: ask for the tag property explicitly; it is not always in the default projection.
        if ($def.key -eq 'ManagedDevice' -and $def.select) { $u += "?`$select=$($def.select)" }
        @{ id = "$($r.Type)|$($r.Id)"; method = 'GET'; url = $u; body = $null }
    })
    $out = @{}
    if (-not $reqs.Count) { return $out }
    $res = Invoke-STMBatch -Requests $reqs
    foreach ($r in $Refs) {
        $k = "$($r.Type)|$($r.Id)"
        $x = $res[$k]
        if ($x -and $x.status -lt 300 -and $x.body) { $out[$k] = @{ Row = (ConvertTo-STMRow -TypeDef (Get-STMTypeDef -Key $r.Type) -Object $x.body); Error = $null; Status = $x.status } }
        else { $out[$k] = @{ Row = $null; Error = if ($x) { $x.error } else { 'No response' }; Status = if ($x) { $x.status } else { 0 } } }
    }
    return $out
}