Files
Intune-Manager/src/Graph.ps1
T
marcoandClaude Opus 4.8 968f47b94f
Build & Release MSI / build-msi (push) Canceled after 0s
v0.1.32 — Bulk-Offboarding aus dem Geraete-Tab, Geraete-Ladefehler behoben
- Bulk-Offboarding aus dem Geraete-Tab (Checkboxen + Alle, POST /api/offboard/resolve)
- Fix "Geraete konnten nicht geladen werden" (400): managementState raus dem $select,
  $orderby entfernt, Namensfilter-Fallback auf deviceName, beta-Endpoint
- Bessere Graph-Fehler-Diagnose (Graph-Body an die Meldung anhaengen)
- Offboard: Grund fuer nicht gefundene Autopilot-Zuordnung sichtbar (autopilotNote)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-11 22:08:46 +02:00

1062 lines
49 KiB
PowerShell

# Microsoft Graph API Helpers
# Verwendet ausschliesslich Microsoft.Graph.Authentication + Invoke-MgGraphRequest,
# um Versionskonflikte zu vermeiden.
function Initialize-GraphModule {
if (Get-Module Microsoft.Graph.Authentication) { return $true }
try {
Import-Module Microsoft.Graph.Authentication -ErrorAction Stop -MinimumVersion 2.0.0
$loaded = Get-Module Microsoft.Graph.Authentication
Write-Host "[GRAPH] Microsoft.Graph.Authentication v$($loaded.Version) geladen" -ForegroundColor DarkGray
return $true
} catch {
$available = @(Get-Module Microsoft.Graph.Authentication -ListAvailable)
if ($available.Count -eq 0) {
throw "Microsoft.Graph.Authentication ist nicht installiert. Bitte ausfuehren: Install-Module Microsoft.Graph.Authentication -Scope CurrentUser -Force"
}
$maxVer = ($available | Sort-Object Version -Descending | Select-Object -First 1).Version
if ($maxVer -lt [version]"2.0.0") {
throw "Microsoft.Graph.Authentication v$maxVer ist zu alt. Mindestens v2.0 noetig. Bitte: Update-Module Microsoft.Graph.Authentication -Scope CurrentUser -Force"
}
throw "Microsoft.Graph.Authentication konnte nicht geladen werden: $($_.Exception.Message)"
}
}
function Invoke-MgGraphRequestRetry {
# Duenner Wrapper um Invoke-MgGraphRequest mit Retry-Backoff fuer 429/503.
# Microsoft-Best-Practice: Throttling (429) immer abfangen und mit
# Retry-After-Verzoegerung erneut versuchen. 503 analog (Service busy).
# Andere Fehler werden unveraendert durchgereicht (kein Verschlucken).
param(
[Parameter(Mandatory=$true)][string]$Uri,
[string]$Method = 'GET',
$Body,
[string]$ContentType,
[hashtable]$Headers,
[int]$MaxRetries = 3,
# Rohes JSON von Graph holen und selbst parsen. Noetig fuer Policy-Exporte:
# Invoke-MgGraphRequest liefert unter Windows PowerShell 5.1 im Hashtable-
# Modus Ein-Element-Collections als Skalar (z.B. printerNames), was beim
# Re-Import 400 "A 'StartArray' node was expected" ausloest. -OutputType Json
# umgeht das: ConvertFrom-Json bewahrt Arrays.
[switch]$AsRawJson
)
$attempt = 0
while ($true) {
try {
$params = @{ Uri = $Uri; Method = $Method }
if ($PSBoundParameters.ContainsKey('Body') -and $null -ne $Body) { $params.Body = $Body }
if ($ContentType) { $params.ContentType = $ContentType }
if ($Headers) { $params.Headers = $Headers }
if ($AsRawJson) {
$params.OutputType = 'Json'
$raw = Invoke-MgGraphRequest @params
if ([string]::IsNullOrWhiteSpace([string]$raw)) { return $null }
if ($PSVersionTable.PSVersion.Major -ge 6) { return ($raw | ConvertFrom-Json -AsHashtable) }
return ($raw | ConvertFrom-Json)
}
return Invoke-MgGraphRequest @params
} catch {
$msg = $_.Exception.Message
$is429 = $msg -match '\b429\b|Too many requests|throttl'
$is503 = $msg -match '\b503\b|Service Unavailable'
if (($is429 -or $is503) -and $attempt -lt $MaxRetries) {
$attempt++
# Retry-After aus dem Fehler ziehen wenn vorhanden, sonst Backoff 2/5/10s.
$wait = $null
if ($msg -match 'Retry-After[:\s]+(\d+)') { $wait = [int]$matches[1] }
if (-not $wait -or $wait -le 0) { $wait = @(2, 5, 10)[[Math]::Min($attempt - 1, 2)] }
$code = if ($is429) { '429' } else { '503' }
Write-Host " [THROTTLE] $code -> Retry $attempt/$MaxRetries in ${wait}s" -ForegroundColor DarkYellow
Start-Sleep -Seconds $wait
continue
}
# Nicht-Retry-Fehler: den Graph-Fehler-Body (mit dem eigentlichen Grund)
# an die Meldung haengen — sonst steht im Log nur "BadRequest".
$gbody = $null
try { $gbody = [string]$_.ErrorDetails.Message } catch {}
if ($gbody) { throw [System.Exception]::new("$msg | Graph: $gbody", $_.Exception) }
throw
}
}
}
function Get-GraphPaged {
param(
[Parameter(Mandatory=$true)][string]$Uri,
# An Invoke-MgGraphRequestRetry durchreichen: bewahrt Arrays fuer Exporte.
[switch]$AsRawJson
)
$results = @()
$next = $Uri
do {
$response = Invoke-MgGraphRequestRetry -Uri $next -Method GET -AsRawJson:$AsRawJson
if ($response.value) { $results += $response.value }
$next = $response.'@odata.nextLink'
} while ($next)
return $results
}
function Get-GraphGroupByFilter {
param(
[string]$Filter,
[string[]]$Property = @("id","displayName"),
[switch]$ExpandMembers
)
$select = "`$select=" + ($Property -join ",").ToLower()
$uri = "https://graph.microsoft.com/v1.0/groups?$select"
if ($Filter) { $uri += "&`$filter=$([uri]::EscapeDataString($Filter))" }
# $expand=members($select=id) liefert bis zu 20 Mitglieder-IDs pro Gruppe —
# genug, um "leer ja/nein" zuverlaessig zu erkennen (Graph cap ist 20).
if ($ExpandMembers) { $uri += "&`$expand=members(`$select=id)" }
return Get-GraphPaged -Uri $uri
}
function Get-GraphGroupById {
param([string]$Id, [string[]]$Property = @("id","displayName"))
$select = "`$select=" + ($Property -join ",").ToLower()
return Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/groups/$Id`?$select" -Method GET
}
function Get-GraphGroupMembers {
param([string]$GroupId)
return Get-GraphPaged -Uri "https://graph.microsoft.com/v1.0/groups/$GroupId/members?`$select=id,displayName,userPrincipalName"
}
function Search-GraphGroups {
# Sucht Gruppen nach displayName. Versucht zuerst startswith (schnell),
# dann $search-Fallback (Substring, braucht ConsistencyLevel: eventual).
param([string]$SearchTerm, [int]$Top = 50)
$term = $SearchTerm -replace "'", "''"
try {
$filter = "startswith(displayName,'$term')"
$uri = "https://graph.microsoft.com/v1.0/groups?`$select=id,displayName,description&`$filter=$([uri]::EscapeDataString($filter))&`$top=$Top"
$resp = Invoke-MgGraphRequest -Uri $uri -Method GET
$items = @()
if ($resp -and $resp.value) { $items = @($resp.value) }
if ($items.Count -gt 0) { return $items }
} catch {
Write-Host " [GSEARCH] startswith fehlgeschlagen: $($_.Exception.Message)" -ForegroundColor DarkYellow
}
try {
$clean = $SearchTerm -replace '"', ''
$searchExpr = [uri]::EscapeDataString('"displayName:' + $clean + '"')
$uri = "https://graph.microsoft.com/v1.0/groups?`$select=id,displayName,description&`$search=$searchExpr&`$top=$Top"
$resp = Invoke-MgGraphRequest -Uri $uri -Method GET -Headers @{ ConsistencyLevel = "eventual" }
if ($resp -and $resp.value) { return @($resp.value) }
} catch {
Write-Host " [GSEARCH] search-Fallback fehlgeschlagen: $($_.Exception.Message)" -ForegroundColor DarkYellow
}
return @()
}
function Resolve-GroupMembersWithNesting {
# Loest alle Benutzer einer Gruppe rekursiv auf (inkl. verschachtelter Unter-
# gruppen). Gibt eine flache Liste zurueck; jeder Eintrag traegt den Pfad
# der Herkunfts-Gruppen (z.B. "Top-Gruppe > Unter-Gruppe").
# Zirkulaere Referenzen werden ueber ein HashSet vermieden.
param(
[Parameter(Mandatory=$true)][string]$GroupId,
[string]$GroupName = "",
[System.Collections.Generic.HashSet[string]]$Visited = $null,
[string[]]$Path = @()
)
if ($null -eq $Visited) {
$Visited = New-Object System.Collections.Generic.HashSet[string]
}
if (-not $Visited.Add($GroupId)) { return @() }
$thisPath = if ($GroupName) { @($Path) + @($GroupName) } else { $Path }
$sourcePath = $thisPath -join " > "
$raw = @()
try {
$raw = @(Get-GraphPaged -Uri "https://graph.microsoft.com/v1.0/groups/$GroupId/members?`$select=id,displayName,userPrincipalName,mail")
} catch {
Write-Host " [EXPORT] Mitglieder von $GroupId konnten nicht geladen werden: $($_.Exception.Message)" -ForegroundColor DarkYellow
return @()
}
$result = [System.Collections.Generic.List[object]]::new()
foreach ($m in $raw) {
$type = [string]$m.'@odata.type'
if ($type -like '*#microsoft.graph.group*') {
$sub = Resolve-GroupMembersWithNesting `
-GroupId ([string]$m.id) `
-GroupName ([string]$m.displayName) `
-Visited $Visited `
-Path $thisPath
foreach ($u in $sub) { $result.Add($u) }
} else {
$result.Add([pscustomobject]@{
Id = [string]$m.id
DisplayName = [string]$m.displayName
UserPrincipalName = [string]$m.userPrincipalName
Mail = [string]$m.mail
SourcePath = $sourcePath
})
}
}
return $result.ToArray()
}
function Get-GraphGroupMembersTransitive {
param([string]$GroupId)
return Get-GraphPaged -Uri "https://graph.microsoft.com/v1.0/groups/$GroupId/transitiveMembers?`$select=id,displayName,userPrincipalName"
}
function Search-GraphUser {
param([string]$SearchTerm)
$term = $SearchTerm -replace "'", "''"
$select = "id,displayName,userPrincipalName,mail,department"
# Welche Felder durchsucht werden ist konfigurierbar (Settings).
$allowed = @('displayName','userPrincipalName','mail','department')
$cfgFields = @($script:Settings.userSearch.fields | Where-Object { $_ -in $allowed })
if ($cfgFields.Count -eq 0) { $cfgFields = @('displayName','userPrincipalName','mail') }
# 1) startswith — schnell, deckt Praefix-Tippen ab (90%+ aller Suchen)
# Bei Umlauten/Nicht-ASCII: ConsistencyLevel + $count erforderlich,
# sonst liefert Graph leere Ergebnisse oder 400.
$hasNonAscii = $term -match '[^\x00-\x7F]'
try {
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$parts = @($cfgFields | ForEach-Object { "startswith($_,'$term')" })
$filter = $parts -join " or "
$uri = "https://graph.microsoft.com/v1.0/users?`$select=$select&`$filter=$([uri]::EscapeDataString($filter))&`$top=25&`$count=true"
$resp = Invoke-MgGraphRequest -Uri $uri -Method GET -Headers @{ ConsistencyLevel = "eventual" }
$items = @()
if ($resp -and $resp.value) { $items = @($resp.value) }
$sw.Stop()
Write-Host " -> User-Search '$SearchTerm' [$($cfgFields -join ',')]: startswith=$($items.Count) Treffer in $($sw.ElapsedMilliseconds)ms" -ForegroundColor DarkGray
if ($items.Count -gt 0) { return $items }
} catch {
Write-Host " -> startswith fehlgeschlagen: $($_.Exception.Message)" -ForegroundColor DarkYellow
}
# 2) Fallback: $search (substring) nur wenn startswith leer war
try {
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$searchTerm = $SearchTerm -replace '"', ''
$parts = @($cfgFields | ForEach-Object { "`"$_`:$searchTerm`"" })
$searchExpr = $parts -join " OR "
$uri = "https://graph.microsoft.com/v1.0/users?`$select=$select&`$top=25&`$search=$([uri]::EscapeDataString($searchExpr))"
$resp = Invoke-MgGraphRequest -Uri $uri -Method GET -Headers @{ ConsistencyLevel = "eventual" }
$items = @()
if ($resp -and $resp.value) { $items = @($resp.value) }
$sw.Stop()
Write-Host " -> User-Search '$SearchTerm': `$search-Fallback=$($items.Count) Treffer in $($sw.ElapsedMilliseconds)ms" -ForegroundColor DarkGray
return $items
} catch {
Write-Host " -> `$search-Fallback fehlgeschlagen: $($_.Exception.Message)" -ForegroundColor DarkYellow
return @()
}
}
function Resolve-GroupNamesBulk {
# Loest viele Gruppen-IDs in einem Schwung via directoryObjects/getByIds auf
# und schreibt {Id => DisplayName} in die uebergebene Hashtable.
param(
[Parameter(Mandatory=$true)][object[]]$Ids,
[Parameter(Mandatory=$true)][hashtable]$Lookup
)
if (-not $Ids -or $Ids.Count -eq 0) { return }
# WICHTIG: zu plain strings casten — sonst wickelt ConvertTo-Json (intern in
# Invoke-MgGraphRequest) PSObject-gewrappte Strings in .Chars und crasht mit
# "Self referencing loop". Genau das hat den Batch unbrauchbar gemacht.
$cleanIds = [string[]]@($Ids | ForEach-Object { [string]$_ } | Where-Object { $_ })
$batchSize = 800 # API-Limit ist 1000, Puffer fuer Safety
for ($i = 0; $i -lt $cleanIds.Count; $i += $batchSize) {
$end = [Math]::Min($i + $batchSize - 1, $cleanIds.Count - 1)
$chunk = [string[]]$cleanIds[$i..$end]
try {
# JSON manuell serialisieren — vermeidet jeden Wrapper-Spass
$bodyJson = @{
ids = $chunk
types = @("group")
} | ConvertTo-Json -Depth 3 -Compress
$resp = Invoke-MgGraphRequest `
-Uri "https://graph.microsoft.com/v1.0/directoryObjects/getByIds" `
-Method POST `
-Body $bodyJson `
-ContentType "application/json"
if ($resp.value) {
foreach ($obj in $resp.value) {
if ($obj.id -and $obj.displayName) {
$Lookup[[string]$obj.id] = [string]$obj.displayName
}
}
}
} catch {
Write-Host " -> getByIds-Batch fehlgeschlagen ($($chunk.Count) IDs): $($_.Exception.Message)" -ForegroundColor DarkYellow
# Fallback nur fuer den fehlgeschlagenen Batch — und auch nur wenn die ID
# noch nicht gesetzt wurde
foreach ($id in $chunk) {
if ($Lookup.ContainsKey($id)) { continue }
try {
$g = Get-GraphGroupById -Id $id -Property @("id","displayName")
if ($g.displayName) { $Lookup[$id] = [string]$g.displayName }
} catch {
$Lookup[$id] = "($id)"
}
}
}
}
}
function New-GraphSecurityGroup {
param([string]$DisplayName, [string]$MailNickname)
$body = @{
displayName = $DisplayName
mailEnabled = $false
securityEnabled = $true
mailNickname = $MailNickname
}
return Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/groups" -Method POST -Body $body
}
function Add-GraphMember {
param([string]$GroupId, [string]$DirectoryObjectId)
# JSON manuell bauen — vermeidet PSObject-Wrapper-Probleme bei der Serialisierung
$bodyJson = '{"@odata.id":"https://graph.microsoft.com/v1.0/directoryObjects/' + $DirectoryObjectId + '"}'
# Out-Null suppressed das $null das Invoke-MgGraphRequest zurueckgibt — sonst
# landet es in der Pipeline des Aufrufers und korrumpiert die Response.
# Ueber den Retry-Wrapper: Member-Adds sind die haeufigste Bulk-Write-Operation
# (Session-Apply mit vielen Empfaengern) und damit am throttle-anfaelligsten.
$null = Invoke-MgGraphRequestRetry `
-Uri "https://graph.microsoft.com/v1.0/groups/$GroupId/members/`$ref" `
-Method POST `
-Body $bodyJson `
-ContentType "application/json"
}
function Get-GraphMobileApps {
param([switch]$WithAssignments)
# WICHTIG: NUR assignments expandieren. categories zusaetzlich auf der
# Vollliste zu expandieren liess Graph hart drosseln (429 -> "Too many
# retries"). Kategorien werden separat + throttle-sicher per $batch
# nachgeladen (Get-GraphMobileAppCategoriesBatch).
$expand = if ($WithAssignments) { "?`$expand=assignments" } else { "" }
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps$expand"
return Get-GraphPaged -Uri $uri
}
function Get-GraphMobileAppCategoriesBatch {
# Liefert eine Map appId -> @(KategorieNamen) fuer die uebergebenen App-IDs
# ueber Microsoft Graph $batch (20 Sub-Requests pro Batch — API-Limit).
# Throttle-sicher: schlaegt ein Batch fehl, werden dessen Apps einfach
# ohne Kategorien gefuehrt — die App-Liste funktioniert unabhaengig davon.
param([string[]]$AppIds)
$map = @{}
if (-not $AppIds -or $AppIds.Count -eq 0) { return $map }
$chunkSize = 20
for ($i = 0; $i -lt $AppIds.Count; $i += $chunkSize) {
$end = [Math]::Min($i + $chunkSize - 1, $AppIds.Count - 1)
$slice = $AppIds[$i..$end]
$requests = @()
foreach ($id in $slice) {
$requests += @{ id = $id; method = 'GET'; url = "/deviceAppManagement/mobileApps/$id/categories" }
}
$body = @{ requests = $requests } | ConvertTo-Json -Depth 5 -Compress
try {
$resp = Invoke-MgGraphRequestRetry -Uri 'https://graph.microsoft.com/beta/$batch' -Method POST -Body $body -ContentType 'application/json'
foreach ($r in @($resp.responses)) {
$rid = [string]$r.id
$st = [int]$r.status
if ($st -eq 200 -and $r.body -and $r.body.value) {
$names = @()
foreach ($cat in @($r.body.value)) {
$n = $null
try { if ($cat.displayName) { $n = [string]$cat.displayName } } catch {}
if (-not $n -and $cat -is [System.Collections.IDictionary] -and $cat['displayName']) { $n = [string]$cat['displayName'] }
if ($n) { $names += $n }
}
$map[$rid] = $names
}
}
} catch {
Write-Host " [CATS-BATCH] Batch $i-$end fehlgeschlagen (uebersprungen): $($_.Exception.Message)" -ForegroundColor DarkYellow
}
}
return $map
}
function Get-GraphMobileAppDetails {
param([Parameter(Mandatory=$true)][string]$AppId)
# Liefert das vollstaendige App-Objekt inkl. typspezifischer Felder
# (Win32: installCommandLine etc., MSI: productCode, Store: licenseType, ...).
return Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId" -Method GET
}
function Add-GraphAppAssignment {
param(
[string]$AppId,
[string]$Intent, # "available" | "required"
[string[]]$GroupId # eine ODER mehrere: GUID(s) und/oder "ALL_USERS"/"ALL_DEVICES"
)
# WICHTIG: Die /assign-Action ERSETZT die komplette Zuweisungsliste der App.
# Ein einzelnes POST wuerde also alle bestehenden Zuweisungen loeschen. Daher:
# bestehende Zuweisungen laden, die neuen mergen (Duplikate ueberspringen) und
# den VOLLEN Satz in EINEM Request schicken. Das haelt mehrere neue Gruppen
# zusammen (kein Read-after-Write-Rennen) und bewahrt vorhandene Zuweisungen.
$newTargets = @()
foreach ($gid in @($GroupId)) {
if ([string]::IsNullOrWhiteSpace([string]$gid)) { continue }
$newTargets += switch ([string]$gid) {
"ALL_USERS" { @{ "@odata.type" = "#microsoft.graph.allLicensedUsersAssignmentTarget" } }
"ALL_DEVICES" { @{ "@odata.type" = "#microsoft.graph.allDevicesAssignmentTarget" } }
default { @{ "@odata.type" = "#microsoft.graph.groupAssignmentTarget"; "groupId" = [string]$gid } }
}
}
$existing = Get-GraphMobileAppAssignments -AppId $AppId
$assignments = @()
$seen = @{} # Schluessel intent|type|groupId -> Duplikate vermeiden
foreach ($a in $existing) {
$tgt = $a.target
if (-not $tgt) { continue }
$key = ([string]$a.intent) + '|' + ([string]$tgt.'@odata.type') + '|' + ([string]$tgt.groupId)
$seen[$key] = $true
$assignments += @{
'@odata.type' = '#microsoft.graph.mobileAppAssignment'
intent = [string]$a.intent
target = $tgt # inkl. evtl. Filter -> unveraendert beibehalten
settings = $a.settings # bestehende Assignment-Settings bewahren
}
}
foreach ($t in $newTargets) {
$key = $Intent + '|' + [string]$t['@odata.type'] + '|' + [string]$t['groupId']
if ($seen.ContainsKey($key)) { continue } # bereits (mit diesem Intent) zugewiesen
$seen[$key] = $true
$assignments += @{
'@odata.type' = '#microsoft.graph.mobileAppAssignment'
intent = $Intent
target = $t
settings = $null
}
}
$body = @{ mobileAppAssignments = @($assignments) }
Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/assign" -Method POST -Body $body
}
function Get-GraphMobileAppAssignments {
param([Parameter(Mandatory=$true)][string]$AppId)
$resp = Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/assignments" -Method GET
if ($resp.value) { return @($resp.value) }
return @()
}
function Remove-GraphAppAssignmentByGroup {
# Loescht jede Zuweisung der App, deren Target zur uebergebenen Group passt.
# Optional kann ein Intent gesetzt werden, dann werden nur Zuweisungen mit
# genau diesem Intent (required/available) entfernt.
param(
[Parameter(Mandatory=$true)][string]$AppId,
[Parameter(Mandatory=$true)][string]$GroupId,
[string]$Intent
)
$assignments = Get-GraphMobileAppAssignments -AppId $AppId
$deleted = @()
foreach ($a in $assignments) {
$tgt = $a.target
if (-not $tgt) { continue }
$tgtType = [string]$tgt.'@odata.type'
$match = $false
switch ($GroupId) {
"ALL_USERS" { if ($tgtType -eq '#microsoft.graph.allLicensedUsersAssignmentTarget') { $match = $true } }
"ALL_DEVICES" { if ($tgtType -eq '#microsoft.graph.allDevicesAssignmentTarget') { $match = $true } }
default {
if ($tgtType -eq '#microsoft.graph.groupAssignmentTarget' -and [string]$tgt.groupId -eq $GroupId) { $match = $true }
}
}
if (-not $match) { continue }
if ($Intent -and ([string]$a.intent) -ne $Intent) { continue }
$null = Invoke-MgGraphRequest `
-Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/assignments/$($a.id)" `
-Method DELETE
$deleted += [pscustomobject]@{
AssignmentId = [string]$a.id
Intent = [string]$a.intent
TargetType = $tgtType
}
}
return $deleted
}
function Update-GraphMobileApp {
# PATCH auf eine MobileApp. Wichtig: '@odata.type' MUSS im Body sein, sonst
# gibt Graph "ResourceNotSupported" / 400 zurueck (polymorpher Typ).
# Versucht beta, faellt bei 400/404/405 auf v1.0 zurueck.
param(
[Parameter(Mandatory=$true)][string]$AppId,
[Parameter(Mandatory=$true)][string]$AppTypeRaw, # z.B. '#microsoft.graph.win32LobApp'
[Parameter(Mandatory=$true)][hashtable]$Patch # z.B. @{ displayName = 'neuer Name' }
)
$body = [ordered]@{}
$body['@odata.type'] = $AppTypeRaw
foreach ($k in $Patch.Keys) { $body[$k] = $Patch[$k] }
$json = $body | ConvertTo-Json -Depth 5 -Compress
$endpoints = @(
"https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId",
"https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps/$AppId"
)
$lastErr = $null
foreach ($uri in $endpoints) {
try {
$null = Invoke-MgGraphRequest -Uri $uri -Method PATCH -Body $json -ContentType "application/json"
return
} catch {
$lastErr = $_
$msg = "$($_.Exception.Message)"
try { $msg += " " + $_.ErrorDetails.Message } catch {}
if ($msg -match '404|400|405|MethodNotAllowed|NotSupported') { continue }
throw
}
}
if ($lastErr) {
$body = $null
try { $body = $lastErr.ErrorDetails.Message } catch {}
$detail = if ($body) { " | Graph-Response: $body" } else { "" }
throw [System.Exception]::new("PATCH fehlgeschlagen: $($lastErr.Exception.Message)$detail")
}
}
# ============================================================
# Content-Update: neue Setup-Datei in eine native App hochladen
# (Phase 1: .intunewin / win32LobApp — vorverschluesselt)
# ============================================================
function Read-IntuneWinPackage {
# Entpackt eine .intunewin (ZIP) und liest die bereits verschluesselte
# Innen-Datei + die EncryptionInfo aus Metadata/Detection.xml. Es wird
# NICHT neu verschluesselt — IntuneWinAppUtil hat das schon getan.
param([Parameter(Mandatory=$true)][string]$Path)
Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction SilentlyContinue
$archive = [System.IO.Compression.ZipFile]::OpenRead($Path)
try {
$detEntry = $archive.Entries | Where-Object { $_.FullName -match 'IntuneWinPackage/Metadata/Detection\.xml$' } | Select-Object -First 1
if (-not $detEntry) { throw "Detection.xml nicht im .intunewin gefunden — ist die Datei wirklich ein IntuneWinAppUtil-Paket?" }
# Detection.xml lesen
$sr = New-Object System.IO.StreamReader($detEntry.Open())
$xmlText = $sr.ReadToEnd(); $sr.Close()
[xml]$xml = $xmlText
$info = $xml.ApplicationInfo
$enc = $info.EncryptionInfo
if (-not $enc) { throw "EncryptionInfo fehlt in Detection.xml" }
$fileName = [string]$info.FileName # innerer Dateiname (z.B. setup.intunewin)
$unencSize = [int64]$info.UnencryptedContentSize
# Innere, bereits verschluesselte Datei extrahieren
$contentEntry = $archive.Entries | Where-Object { $_.FullName -match "IntuneWinPackage/Contents/.+" } | Select-Object -First 1
if (-not $contentEntry) { throw "Verschluesselte Innen-Datei (Contents/) nicht gefunden" }
$ms = New-Object System.IO.MemoryStream
$cs = $contentEntry.Open()
$cs.CopyTo($ms); $cs.Close()
$encryptedBytes = $ms.ToArray(); $ms.Dispose()
return @{
EncryptedBytes = $encryptedBytes
Size = $unencSize
SizeEncrypted = [int64]$encryptedBytes.Length
FileName = $fileName
EncryptionInfo = @{
'@odata.type' = '#microsoft.graph.fileEncryptionInfo'
encryptionKey = [string]$enc.EncryptionKey
macKey = [string]$enc.MacKey
initializationVector = [string]$enc.InitializationVector
mac = [string]$enc.Mac
profileIdentifier = [string]$enc.ProfileIdentifier
fileDigest = [string]$enc.FileDigest
fileDigestAlgorithm = [string]$enc.FileDigestAlgorithm
}
}
} finally {
$archive.Dispose()
}
}
function New-GraphAppContentVersion {
# Schritt 1: neue contentVersion anlegen. GraphType z.B. 'win32LobApp'.
param([string]$AppId, [string]$GraphType)
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/$GraphType/contentVersions"
$resp = Invoke-MgGraphRequestRetry -Uri $uri -Method POST -Body '{}' -ContentType 'application/json'
$cvId = if ($resp.id) { [string]$resp.id } else { [string]$resp.Id }
if (-not $cvId) { throw "contentVersion-Anlage lieferte keine id zurueck" }
return $cvId
}
function New-GraphAppContentFile {
# Schritt 2: File-Eintrag in der contentVersion anlegen (mit Klartext-Size +
# verschluesselter Size). Liefert fileId.
param(
[string]$AppId, [string]$GraphType, [string]$CvId,
[string]$Name, [int64]$Size, [int64]$SizeEncrypted, $Manifest = $null
)
$body = [ordered]@{
'@odata.type' = '#microsoft.graph.mobileAppContentFile'
name = $Name
size = $Size
sizeEncrypted = $SizeEncrypted
isDependency = $false
}
if ($Manifest) { $body['manifest'] = $Manifest } # base64 (MSI/MSIX); win32 = weglassen
$json = $body | ConvertTo-Json -Depth 5 -Compress
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/$GraphType/contentVersions/$CvId/files"
$resp = Invoke-MgGraphRequestRetry -Uri $uri -Method POST -Body $json -ContentType 'application/json'
$fileId = if ($resp.id) { [string]$resp.id } else { [string]$resp.Id }
if (-not $fileId) { throw "File-Anlage lieferte keine id zurueck" }
return $fileId
}
function Get-GraphAppContentFile {
param([string]$AppId, [string]$GraphType, [string]$CvId, [string]$FileId)
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/$GraphType/contentVersions/$CvId/files/$FileId"
return Invoke-MgGraphRequestRetry -Uri $uri -Method GET
}
function Wait-GraphContentFileState {
# Schritt 3/6: pollt den File-Eintrag bis TargetState erreicht ist.
# Bricht bei *Failed-Zustaenden und Timeout ab.
param(
[string]$AppId, [string]$GraphType, [string]$CvId, [string]$FileId,
[string]$TargetState, [int]$TimeoutSec = 180
)
$deadline = (Get-Date).AddSeconds($TimeoutSec)
while ($true) {
$f = Get-GraphAppContentFile -AppId $AppId -GraphType $GraphType -CvId $CvId -FileId $FileId
$state = if ($f.uploadState) { [string]$f.uploadState } else { [string]$f.uploadstate }
if ($state -eq $TargetState) { return $f }
if ($state -match 'Failed') { throw "Upload-State '$state' (erwartet '$TargetState') — Graph hat den Schritt abgelehnt." }
if ((Get-Date) -gt $deadline) { throw "Timeout beim Warten auf '$TargetState' (letzter State: '$state')." }
Start-Sleep -Milliseconds 1500
}
}
function Send-GraphContentToAzureBlob {
# Schritt 4: verschluesselte Bytes als Block-Blob in die SAS-URL laden.
# Chunked (6 MB). WICHTIG: die Bytes werden als ISO-8859-1-String gesendet
# (1:1 Byte<->Zeichen) mit content-type 'text/plain; charset=iso-8859-1' —
# NICHT als rohes byte[]. Invoke-WebRequest verfaelscht in PS 5.1 binaere
# byte[]-Bodies (Bytes > 127), was korrupten Content nach Azure laedt.
# Schema 1:1 aus der MSEndpointMgr/IntuneWin32App-Referenz uebernommen.
param([Parameter(Mandatory=$true)][string]$SasUri, [Parameter(Mandatory=$true)][byte[]]$Bytes)
$isoEncoding = [System.Text.Encoding]::GetEncoding("iso-8859-1")
$chunkSize = 6 * 1024 * 1024
$total = $Bytes.Length
$blockIds = New-Object System.Collections.Generic.List[string]
$idx = 0
for ($offset = 0; $offset -lt $total; $offset += $chunkSize) {
$len = [Math]::Min($chunkSize, $total - $offset)
$chunk = New-Object byte[] $len
[Array]::Copy($Bytes, $offset, $chunk, 0, $len)
# Block-ID: base64 einer 0-gepaddeten Nummer (gleiche Laenge fuer alle)
$blockId = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($idx.ToString('D6')))
$blockIds.Add($blockId)
$encodedChunk = $isoEncoding.GetString($chunk)
$putUri = "$SasUri&comp=block&blockid=$([uri]::EscapeDataString($blockId))"
$headers = @{ 'x-ms-blob-type' = 'BlockBlob'; 'content-type' = 'text/plain; charset=iso-8859-1' }
Invoke-WebRequest -Uri $putUri -Method PUT -Headers $headers -Body $encodedChunk -UseBasicParsing | Out-Null
$idx++
}
# Block-Liste committen (Invoke-RestMethod, content-type text/plain; charset=UTF-8)
$xml = '<?xml version="1.0" encoding="utf-8"?><BlockList>'
foreach ($b in $blockIds) { $xml += "<Latest>$b</Latest>" }
$xml += '</BlockList>'
$listUri = "$SasUri&comp=blocklist"
Invoke-RestMethod -Uri $listUri -Method PUT -Body $xml -Headers @{ 'content-type' = 'text/plain; charset=UTF-8' } | Out-Null
}
function Invoke-GraphContentRenewUpload {
param([string]$AppId, [string]$GraphType, [string]$CvId, [string]$FileId)
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/$GraphType/contentVersions/$CvId/files/$FileId/renewUpload"
$null = Invoke-MgGraphRequestRetry -Uri $uri -Method POST
}
function Invoke-GraphContentCommit {
# Schritt 5: commit mit fileEncryptionInfo.
param([string]$AppId, [string]$GraphType, [string]$CvId, [string]$FileId, [hashtable]$EncryptionInfo)
$body = @{ fileEncryptionInfo = $EncryptionInfo } | ConvertTo-Json -Depth 5 -Compress
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/$GraphType/contentVersions/$CvId/files/$FileId/commit"
$null = Invoke-MgGraphRequestRetry -Uri $uri -Method POST -Body $body -ContentType 'application/json'
}
function Update-GraphAppContent {
# Orchestrator: laedt eine neue Setup-Datei hoch und aktiviert sie.
# Phase 1 unterstuetzt .intunewin (win32LobApp). $ProgressCb (scriptblock)
# optional fuer Schritt-Logging. Gibt das Ergebnis-Objekt zurueck.
param(
[Parameter(Mandatory=$true)][string]$AppId,
[Parameter(Mandatory=$true)][string]$GraphTypeRaw, # z.B. '#microsoft.graph.win32LobApp'
[Parameter(Mandatory=$true)][string]$FilePath,
[string]$DisplayVersion,
[scriptblock]$ProgressCb
)
$report = { param($step) if ($ProgressCb) { & $ProgressCb $step } ; Write-Host " [CONTENT] $step" -ForegroundColor DarkCyan }
$graphType = ($GraphTypeRaw -replace '^#microsoft\.graph\.', '') # win32LobApp
$odataCast = "graph.$graphType"
# 1) Paket lesen (Phase 1: nur .intunewin)
& $report "Lese Paket"
$ext = [IO.Path]::GetExtension($FilePath).ToLower()
if ($ext -ne '.intunewin') { throw "Phase 1 unterstuetzt nur .intunewin. Datei: $ext" }
$pkg = Read-IntuneWinPackage -Path $FilePath
# 2) contentVersion + file anlegen
& $report "Lege Content-Version an"
$cvId = New-GraphAppContentVersion -AppId $AppId -GraphType $odataCast
$fileId = New-GraphAppContentFile -AppId $AppId -GraphType $odataCast -CvId $cvId -Name $pkg.FileName -Size $pkg.Size -SizeEncrypted $pkg.SizeEncrypted
# 3) auf SAS warten
& $report "Warte auf Azure-Speicher-URL"
$f = Wait-GraphContentFileState -AppId $AppId -GraphType $odataCast -CvId $cvId -FileId $fileId -TargetState 'azureStorageUriRequestSuccess' -TimeoutSec 120
$sas = if ($f.azureStorageUri) { [string]$f.azureStorageUri } else { [string]$f.azurestorageuri }
if (-not $sas) { throw "Keine azureStorageUri erhalten" }
# 4) Upload zu Azure Blob
& $report "Lade Datei hoch ($([int]($pkg.SizeEncrypted/1MB)) MB)"
Send-GraphContentToAzureBlob -SasUri $sas -Bytes $pkg.EncryptedBytes
# 5) commit
& $report "Committe Datei"
Invoke-GraphContentCommit -AppId $AppId -GraphType $odataCast -CvId $cvId -FileId $fileId -EncryptionInfo $pkg.EncryptionInfo
# 6) auf commit-Erfolg warten
& $report "Warte auf Commit-Bestaetigung"
$null = Wait-GraphContentFileState -AppId $AppId -GraphType $odataCast -CvId $cvId -FileId $fileId -TargetState 'commitFileSuccess' -TimeoutSec 180
# 7) App auf neue Version zeigen (+ optional displayVersion)
& $report "Aktiviere neue Version"
$patch = @{ committedContentVersion = $cvId }
if ($DisplayVersion) { $patch['displayVersion'] = $DisplayVersion }
Update-GraphMobileApp -AppId $AppId -AppTypeRaw $GraphTypeRaw -Patch $patch
& $report "Fertig"
return @{ ok = $true; contentVersion = $cvId; fileId = $fileId; size = $pkg.Size; sizeEncrypted = $pkg.SizeEncrypted; displayVersion = $DisplayVersion }
}
function Get-GraphAppDetailsBatch {
# Holt App-Stammdaten + installSummary + relationships in EINEM
# HTTP-Roundtrip via Microsoft Graph $batch. Server-seitig parallelisiert
# — statt 3 sequenzieller Calls (jeder ~300-800ms) nur ein einziger
# Roundtrip in der Zeit des langsamsten Sub-Calls.
# Falls ein Sub-Call serverseitig fehlschlaegt, wird der jeweilige
# Teil $null gesetzt — der Rest funktioniert weiter.
param([Parameter(Mandatory=$true)][string]$AppId)
$body = @{
requests = @(
@{ id = 'app'; method = 'GET'; url = "/deviceAppManagement/mobileApps/$($AppId)?`$expand=categories" },
@{ id = 'summary'; method = 'GET'; url = "/deviceAppManagement/mobileApps/$AppId/installSummary" },
@{ id = 'rels'; method = 'GET'; url = "/deviceAppManagement/mobileApps/$AppId/relationships" }
)
}
$json = $body | ConvertTo-Json -Depth 5 -Compress
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$resp = $null
try {
$resp = Invoke-MgGraphRequest `
-Uri 'https://graph.microsoft.com/beta/$batch' `
-Method POST `
-Body $json `
-ContentType 'application/json'
} catch {
Write-Host " [BATCH] $AppId fehlgeschlagen: $($_.Exception.Message)" -ForegroundColor DarkYellow
return @{ App = $null; InstallSummary = $null; Relationships = @() }
}
$sw.Stop()
$result = @{ App = $null; InstallSummary = $null; Relationships = @() }
$stati = @()
foreach ($r in @($resp.responses)) {
$st = [int]$r.status
$id = [string]$r.id
$stati += "$id=$st"
switch ($id) {
'app' {
if ($st -eq 200) { $result.App = $r.body }
}
'summary' {
if ($st -eq 200) { $result.InstallSummary = $r.body }
}
'rels' {
if ($st -eq 200 -and $r.body.value) {
$result.Relationships = @($r.body.value)
}
}
}
}
Write-Host " [BATCH] $AppId in $($sw.ElapsedMilliseconds)ms ($($stati -join ', '))" -ForegroundColor DarkGray
return $result
}
function Get-GraphMobileAppInstallSummary {
# Installations-Statistik einer App. Endpoint ist Singular ("installSummary"),
# nicht zu verwechseln mit deviceStatuses/userStatuses (Per-Device/Per-User).
param([Parameter(Mandatory=$true)][string]$AppId)
try {
return Invoke-MgGraphRequest `
-Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/installSummary" `
-Method GET
} catch {
return $null
}
}
function Get-GraphMobileAppRelationships {
# Liefert die Beziehungen einer App (Dependency / Supersedence). 400-Fehler
# beim Delete kommen oft daher, dass eine andere App diese App als Dependency
# oder Supersedence referenziert - dann muss erst die Gegenseite entfernt werden.
param([Parameter(Mandatory=$true)][string]$AppId)
try {
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/relationships"
$resp = Invoke-MgGraphRequest -Uri $uri -Method GET
$items = @()
if ($resp.value) { $items = @($resp.value) }
Write-Host " [RELS] $AppId -> $($items.Count) Eintraege via /relationships" -ForegroundColor DarkGray
if ($items.Count -gt 0) {
$byType = $items | Group-Object { [string]$_.'@odata.type' } | ForEach-Object { "$($_.Name)=$($_.Count)" }
Write-Host " [RELS] Typen: $($byType -join ', ')" -ForegroundColor DarkGray
}
return $items
} catch {
Write-Host " [RELS] Lesen fehlgeschlagen fuer $AppId : $($_.Exception.Message)" -ForegroundColor DarkYellow
return @()
}
}
function Remove-GraphMobileApp {
# Versucht die App ueber beta zu loeschen; fallback auf v1.0 falls beta 400/404 gibt.
# Wirft eine angereicherte Exception mit der Original-Graph-Fehlermeldung.
param([Parameter(Mandatory=$true)][string]$AppId)
$endpoints = @(
"https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId",
"https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps/$AppId"
)
$lastErr = $null
foreach ($uri in $endpoints) {
try {
$null = Invoke-MgGraphRequest -Uri $uri -Method DELETE
return # success
} catch {
$lastErr = $_
# ErrorDetails.Message ist meist der Raw-JSON-Body von Graph
$body = $null
try { $body = $_.ErrorDetails.Message } catch {}
# 405/Resource-not-found auf beta -> v1.0 probieren. Bei 400 ebenfalls
# einen Versuch wagen, das ist im Test mit win32LobApp gelegentlich noetig.
$msg = "$($_.Exception.Message) $body"
if ($msg -match '404|400|405|MethodNotAllowed|NotSupported') {
continue
} else {
throw
}
}
}
# Beide Endpoints haben versagt -> letzte Fehlermeldung anreichern und werfen
if ($lastErr) {
$body = $null
try { $body = $lastErr.ErrorDetails.Message } catch {}
$detail = if ($body) { " | Graph-Response: $body" } else { "" }
throw [System.Exception]::new("Delete fehlgeschlagen: $($lastErr.Exception.Message)$detail")
}
}
# Ausgeschlossene App-Typen: iOS/Android bleiben ausgeblendet (dieses Tool ist auf
# Windows + macOS ausgelegt). macOS-Typen sind bewusst NICHT mehr ausgeschlossen,
# damit Mac-Apps in Liste/Suche erscheinen.
$script:ExcludedAppTypes = @(
'#microsoft.graph.iosLobApp', '#microsoft.graph.iosStoreApp', '#microsoft.graph.iosVppApp',
'#microsoft.graph.managedIOSLobApp', '#microsoft.graph.managedIOSStoreApp',
'#microsoft.graph.androidLobApp', '#microsoft.graph.androidStoreApp', '#microsoft.graph.androidForWorkApp',
'#microsoft.graph.androidManagedStoreApp', '#microsoft.graph.androidManagedStoreWebApp',
'#microsoft.graph.managedAndroidLobApp', '#microsoft.graph.managedAndroidStoreApp'
)
function Test-AppTypeAllowed {
param([string]$Type)
return -not ($script:ExcludedAppTypes -contains $Type)
}
function ConvertTo-AppFriendlyType {
param([string]$Type)
switch ($Type) {
'#microsoft.graph.win32LobApp' { 'Win32' }
'#microsoft.graph.windowsStoreApp' { 'Store' }
'#microsoft.graph.microsoftStoreForBusinessApp' { 'MS Store' }
'#microsoft.graph.officeSuiteApp' { 'M365 Apps' }
'#microsoft.graph.windowsMicrosoftEdgeApp' { 'Edge' }
'#microsoft.graph.windowsWebApp' { 'WebApp' }
'#microsoft.graph.winGetApp' { 'WinGet' }
'#microsoft.graph.windowsPhone81AppX' { 'APPX' }
'#microsoft.graph.windowsAppX' { 'APPX' }
'#microsoft.graph.windowsUniversalAppX' { 'APPX' }
'#microsoft.graph.windowsMobileMSI' { 'MSI' }
'#microsoft.graph.macOSDmgApp' { 'macOS DMG' }
'#microsoft.graph.macOSPkgApp' { 'macOS PKG' }
'#microsoft.graph.macOSLobApp' { 'macOS LOB' }
'#microsoft.graph.macOSMicrosoftDefenderApp' { 'macOS Defender' }
'#microsoft.graph.macOSMicrosoftEdgeApp' { 'macOS Edge' }
'#microsoft.graph.macOSOfficeSuiteApp' { 'macOS M365' }
'#microsoft.graph.macOsVppApp' { 'macOS VPP' }
default {
($Type -replace '#microsoft\.graph\.','')
}
}
}
function Get-GraphErrorFriendly {
param([Parameter(Mandatory=$true)]$ErrorRecord)
$msg = $ErrorRecord.Exception.Message
switch -Regex ($msg) {
"already exist|bereits vorhanden|One or more added object references already exist" {
return @{ Code="MemberExists"; Friendly="Mitglied bereits in Gruppe"; IsWarning=$true; Full=$msg }
}
"Insufficient privileges|Access denied|Authorization_RequestDenied|403" {
return @{ Code="Forbidden(403)"; Friendly="Keine Berechtigung. Erforderlich: Group.ReadWrite.All / DeviceManagementApps.ReadWrite.All"; IsWarning=$false; Full=$msg }
}
"does not exist|not found|Request_ResourceNotFound|404" {
return @{ Code="NotFound(404)"; Friendly="Objekt nicht gefunden"; IsWarning=$false; Full=$msg }
}
"Too many requests|throttled|429" {
return @{ Code="Throttled(429)"; Friendly="Zu viele Anfragen. Bitte warten."; IsWarning=$false; Full=$msg }
}
"BadRequest|400" {
if ($msg -match "exist|vorhanden|member") {
return @{ Code="MemberExists"; Friendly="Mitglied bereits in Gruppe"; IsWarning=$true; Full=$msg }
}
return @{ Code="BadRequest(400)"; Friendly="Ungueltige Anfrage"; IsWarning=$false; Full=$msg }
}
default {
return @{ Code="Error"; Friendly=$msg; IsWarning=$false; Full=$msg }
}
}
}
function Test-AppVendorRule {
# True wenn die App den angegebenen Detection-Regel-Block matcht.
param($RawApp, $Rule)
if (-not $Rule -or -not $Rule.field -or -not $Rule.pattern) { return $false }
$value = switch ($Rule.field) {
'commandLine' { @($RawApp.installCommandLine, $RawApp.uninstallCommandLine) -join " " }
'developer' { [string]$RawApp.developer }
'publisher' { [string]$RawApp.publisher }
'displayName' { [string]$RawApp.displayName }
'notes' { [string]$RawApp.notes }
'owner' { [string]$RawApp.owner }
default { "" }
}
if (-not $value) { return $false }
switch ($Rule.match) {
'equals' { return ($value -eq $Rule.pattern) }
'startsWith' { return $value.StartsWith($Rule.pattern, [StringComparison]::OrdinalIgnoreCase) }
'regex' {
try { return ($value -match $Rule.pattern) }
catch { return $false } # ungueltiger Regex -> Vendor matcht halt nicht
}
default { return ($value -match [regex]::Escape($Rule.pattern)) } # 'contains'
}
}
function Resolve-AppVendorSource {
# Iteriert ueber Settings.vendors und liefert displayName des ersten
# passenden Vendors. Default: "Intune" wenn keiner matcht.
param($RawApp, $Vendors)
if ($null -eq $Vendors) { return "Intune" }
foreach ($v in @($Vendors)) {
if ($v -and (Test-AppVendorRule -RawApp $RawApp -Rule $v.detection)) {
return [string]$v.displayName
}
}
return "Intune"
}
function Format-AppForFrontend {
param($RawApp, $AllGroupsLookup)
# AllGroupsLookup: hashtable groupId -> displayName (fuer Anzeige der zugewiesenen Gruppen)
$available = @()
$required = @()
foreach ($a in @($RawApp.assignments)) {
$tgt = $a.target
$tgtType = $tgt.'@odata.type'
$entry = $null
if ($tgtType -eq '#microsoft.graph.allLicensedUsersAssignmentTarget') {
$entry = @{ GroupId="ALL_USERS"; GroupName="All Users"; IsNative=$true }
} elseif ($tgtType -eq '#microsoft.graph.allDevicesAssignmentTarget') {
$entry = @{ GroupId="ALL_DEVICES"; GroupName="All Devices"; IsNative=$true }
} elseif ($tgtType -eq '#microsoft.graph.groupAssignmentTarget') {
$gid = $tgt.groupId
$name = if ($AllGroupsLookup -and $AllGroupsLookup.ContainsKey($gid)) { $AllGroupsLookup[$gid] } else { $gid }
$entry = @{ GroupId=$gid; GroupName=$name; IsNative=$false }
} elseif ($tgtType -eq '#microsoft.graph.exclusionGroupAssignmentTarget') {
continue
}
if ($null -ne $entry) {
switch ($a.intent) {
'available' { $available += $entry }
'required' { $required += $entry }
}
}
}
# Version aus moeglichen Feldern (je nach App-Typ)
$version = $null
foreach ($f in @('displayVersion','version','productVersion','identityVersion','officeSuiteAppVersion')) {
if ($RawApp.$f) { $version = [string]$RawApp.$f; break }
}
# Quelle: PMPC-Direkterkennung zuerst (das hat schon immer funktioniert,
# bleibt damit auch bei kaputter Settings/Vendor-Registry zuverlaessig).
# Erst wenn das nicht greift, fragen wir die Vendor-Registry — dort liegen
# Robopack & weitere konfigurierbare Vendoren.
$source = "Intune"
if ($RawApp.installCommandLine -and $RawApp.installCommandLine -match "PatchMyPC") {
$source = "PatchMyPC"
} elseif ($RawApp.uninstallCommandLine -and $RawApp.uninstallCommandLine -match "PatchMyPC") {
$source = "PatchMyPC"
} else {
$vendorSource = Resolve-AppVendorSource -RawApp $RawApp -Vendors $script:Settings.vendors
if ($vendorSource -and $vendorSource -ne "Intune" -and $vendorSource -ne "PatchMyPC") {
$source = $vendorSource
}
}
return [pscustomobject]@{
AppId = $RawApp.id
AppName = $RawApp.displayName
AppType = ConvertTo-AppFriendlyType -Type $RawApp.'@odata.type'
AppTypeRaw = $RawApp.'@odata.type'
Publisher = $RawApp.publisher
Version = $version
Source = $source
IsAssigned = ($RawApp.isAssigned -eq $true)
AvailableGroups = $available
RequiredGroups = $required
AvailableCount = $available.Count
RequiredCount = $required.Count
# Kategorien fuer Filter + Anzeige. Get-AppCategoryNames liegt in Api.ps1,
# ist aber global dot-sourced. Liefert immer ein String-Array (ggf. leer).
Categories = (Get-AppCategoryNames -RawCategories $RawApp.categories -AppId $RawApp.id)
# ISO-Strings damit JS new Date() es zuverlaessig parst — fuer Filter
# nach Aenderungs-Zeitraum (App-Liste, ohne Detail-Roundtrip).
CreatedDateTime = ConvertTo-IsoDate $RawApp.createdDateTime
LastModifiedDateTime = ConvertTo-IsoDate $RawApp.lastModifiedDateTime
}
}