Group Management: Geräte per CSV in Gruppen aufnehmen

CSV-Import bekommt einen Modus-Umschalter "Benutzer | Geräte". Im Geräte-Modus
werden Gerätenamen ODER Seriennummern aufgelöst (neuer Endpoint
POST /api/groups/resolve-devices: managedDevice per deviceName/serialNumber ->
azureADDeviceId -> Entra-Geräte-Objekt-Id). Rückgabeformat identisch zu
resolve-upns, daher funktionieren Vorschau und Import (Add-GroupMembersEndpoint)
unverändert; UserId ist hier die Entra-Objekt-Id.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
marcoandClaude Opus 4.8 committed 2026-11-11 11:07:51 +01:00
1 parent 15441eab35
commit 7ffb43f938
4 files changed
+193 -10

No files matched your search

+99
View File
@@ -34,6 +34,7 @@ function Invoke-ApiHandler {
"POST /api/groups" { return New-GroupEndpoint -Body $Body } "POST /api/groups" { return New-GroupEndpoint -Body $Body }
"POST /api/groups/check" { return Test-GroupNameEndpoint -Body $Body } "POST /api/groups/check" { return Test-GroupNameEndpoint -Body $Body }
"POST /api/groups/resolve-upns" { return Resolve-UpnsEndpoint -Body $Body } "POST /api/groups/resolve-upns" { return Resolve-UpnsEndpoint -Body $Body }
"POST /api/groups/resolve-devices" { return Resolve-DevicesEndpoint -Body $Body }
"GET /api/users" { return Search-UsersEndpoint -Query $Query } "GET /api/users" { return Search-UsersEndpoint -Query $Query }
@@ -1583,6 +1584,104 @@ function Resolve-UpnsEndpoint {
return @{ items = @($resolved); found = $found.Count; notFound = $notFound.Count } return @{ items = @($resolved); found = $found.Count; notFound = $notFound.Count }
} }
function Resolve-DevicesEndpoint {
# Loest Geraete-Bezeichner (GERAETENAME ODER SERIENNUMMER, auto) zu Entra-
# Geraete-OBJEKT-IDs auf (fuer die Gruppen-Aufnahme). Rueckgabeformat wie
# Resolve-UpnsEndpoint (Upn/UserId/DisplayName/Mail/Found) -> die CSV-Vorschau
# und der Import funktionieren unveraendert; UserId ist hier die Entra-Objekt-Id.
param($Body)
$err = Test-Connected
if ($err) { return $err }
$idsRaw = @($Body.identifiers | ForEach-Object { [string]$_.Trim() } | Where-Object { $_ -ne '' })
if ($idsRaw.Count -eq 0) { return @{ __status = 400; error = 'identifiers fehlt oder leer' } }
$ids = @($idsRaw | Select-Object -Unique)
Write-Host "[IMPORT] Loese $($ids.Count) Geraete auf (Name/Serial)..." -ForegroundColor DarkCyan
$sel = 'id,deviceName,serialNumber,azureADDeviceId,manufacturer,model'
# Pass 1: managedDevice per Geraetename (exakt).
$md = @{} # identifier(lower) -> managedDevice
$reqs = @(); $i = 0
foreach ($id in $ids) {
$esc = $id -replace "'", "''"
$f = [Uri]::EscapeDataString("deviceName eq '$esc'")
$reqs += @{ id = "n$i"; method = 'GET'; url = "/deviceManagement/managedDevices?`$filter=$f&`$select=$sel&`$top=1" }
$i++
}
$b1 = Invoke-GraphBatch -Requests $reqs
for ($j = 0; $j -lt $ids.Count; $j++) {
$r = $b1["n$j"]
if ($r -and [int]$r.status -eq 200 -and @($r.body.value).Count -gt 0) { $md[$ids[$j].ToLower()] = @($r.body.value)[0] }
}
# Pass 2: nicht per Name Gefundene per Seriennummer.
$unresolved = @($ids | Where-Object { -not $md.ContainsKey($_.ToLower()) })
if ($unresolved.Count -gt 0) {
$reqs = @(); $i = 0
foreach ($id in $unresolved) {
$esc = $id -replace "'", "''"
$f = [Uri]::EscapeDataString("serialNumber eq '$esc'")
$reqs += @{ id = "s$i"; method = 'GET'; url = "/deviceManagement/managedDevices?`$filter=$f&`$select=$sel&`$top=1" }
$i++
}
$b2 = Invoke-GraphBatch -Requests $reqs
for ($j = 0; $j -lt $unresolved.Count; $j++) {
$r = $b2["s$j"]
if ($r -and [int]$r.status -eq 200 -and @($r.body.value).Count -gt 0) { $md[$unresolved[$j].ToLower()] = @($r.body.value)[0] }
}
}
# Pass 3: azureADDeviceId -> Entra-Geraete-Objekt-Id (fuer die Gruppen-Aufnahme).
$aads = @($md.Values | ForEach-Object { [string]$_.azureADDeviceId } | Where-Object { $_ -and $_ -ne '00000000-0000-0000-0000-000000000000' } | Select-Object -Unique)
$entraByAad = @{}
if ($aads.Count -gt 0) {
$reqs = @(); $i = 0
foreach ($aad in $aads) {
$f = [Uri]::EscapeDataString("deviceId eq '$aad'")
$reqs += @{ id = "e$i"; method = 'GET'; url = "/devices?`$filter=$f&`$select=id,displayName,deviceId&`$top=1" }
$i++
}
$b3 = Invoke-GraphBatch -Requests $reqs
for ($j = 0; $j -lt $aads.Count; $j++) {
$r = $b3["e$j"]
if ($r -and [int]$r.status -eq 200 -and @($r.body.value).Count -gt 0) { $entraByAad[$aads[$j]] = @($r.body.value)[0] }
}
}
$resolved = [System.Collections.Generic.List[object]]::new()
foreach ($id in $ids) {
$m = $null
if ($md.ContainsKey($id.ToLower())) { $m = $md[$id.ToLower()] }
$objId = ''; $info = ''
$dn = ''
if ($m) {
$dn = [string]$m.deviceName
$aad = [string]$m.azureADDeviceId
if ($aad -and $entraByAad.ContainsKey($aad)) {
$ent = $entraByAad[$aad]
if ($ent.id) { $objId = [string]$ent.id }
}
$sn = [string]$m.serialNumber
$hw = ((@([string]$m.manufacturer, [string]$m.model) | Where-Object { $_ }) -join ' ').Trim()
$parts = @(); if ($sn) { $parts += "SN $sn" }; if ($hw) { $parts += $hw }
$info = ($parts -join ' - ')
}
$resolved.Add([pscustomobject]@{
Upn = $id
UserId = $objId
DisplayName = $dn
Mail = $info
Found = [bool]$objId
})
}
$found = @($resolved | Where-Object { $_.Found })
$notFound = @($resolved | Where-Object { -not $_.Found })
Write-Host " -> $($found.Count) Geraete aufgeloest, $($notFound.Count) nicht gefunden" -ForegroundColor DarkGray
return @{ items = @($resolved); found = $found.Count; notFound = $notFound.Count }
}
function Remove-GroupMemberEndpoint { function Remove-GroupMemberEndpoint {
param([string]$GroupId, [string]$UserId) param([string]$GroupId, [string]$UserId)
$err = Test-Connected $err = Test-Connected
+64 -8
View File
@@ -5580,6 +5580,7 @@ const CsvImport = {
resolved: [], // Ergebnis des letzten Resolve-Calls resolved: [], // Ergebnis des letzten Resolve-Calls
groupId: '', groupId: '',
groupName: '', groupName: '',
mode: 'users', // 'users' | 'devices'
}; };
// Datei-Upload -> Textarea füllen // Datei-Upload -> Textarea füllen
@@ -5644,20 +5645,74 @@ function parseCsvUpns(raw) {
return [...new Set(upns)]; return [...new Set(upns)];
} }
// Geräte-Bezeichner (Gerätename ODER Seriennummer) aus CSV extrahieren.
function parseCsvDevices(raw) {
const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
if (lines.length === 0) return [];
const HEADERS = ['devicename', 'gerätename', 'geraetename', 'name', 'serialnumber', 'seriennummer', 'serial', 'sn'];
const firstFields = splitCsvLine(lines[0]).map(f => f.toLowerCase());
let colIdx = -1;
for (const h of HEADERS) { const idx = firstFields.indexOf(h); if (idx !== -1) { colIdx = idx; break; } }
const startLine = colIdx !== -1 ? 1 : 0;
if (colIdx === -1) colIdx = 0; // kein Header -> erste Spalte
const out = [];
for (let i = startLine; i < lines.length; i++) {
const val = (splitCsvLine(lines[i])[colIdx] || '').trim();
if (val) out.push(val);
}
return [...new Set(out)];
}
// Beschriftungen je Modus (Benutzer vs. Geräte) umschalten.
function csvResolveLabel() { return CsvImport.mode === 'devices' ? 'Geräte auflösen' : 'Benutzer auflösen'; }
function csvApplyModeLabels() {
const dev = CsvImport.mode === 'devices';
const t = document.getElementById('csvImportTitle');
if (t) t.textContent = dev ? 'Gerätenamen/Seriennummern einfügen oder CSV hochladen' : 'UPNs einfügen oder CSV hochladen';
const ta = document.getElementById('csvImportText');
if (ta) ta.placeholder = dev
? 'Ein Gerätename oder eine Seriennummer pro Zeile\n(oder erste Spalte einer CSV, Header wird erkannt).'
: 'Eine UPN/E-Mail pro Zeile, z.B.\nmax.mustermann@firma.de\nerika.muster@firma.de\n\nOder erste Spalte einer CSV (Header wird erkannt).';
const ch = document.getElementById('csvPreviewColHead');
if (ch) ch.textContent = dev ? 'Gerät (Name/Serial)' : 'UPN / E-Mail';
const rb = document.getElementById('csvResolveBtn');
if (rb) rb.textContent = csvResolveLabel();
}
document.querySelectorAll('input[name="csvImportMode"]').forEach(radio => {
radio.addEventListener('change', () => {
if (!radio.checked) return;
CsvImport.mode = radio.value === 'devices' ? 'devices' : 'users';
CsvImport.resolved = [];
document.getElementById('csvPreviewWrap')?.classList.add('hidden');
document.getElementById('csvResultBanner')?.classList.add('hidden');
document.getElementById('csvResolveStats').textContent = '';
csvApplyModeLabels();
updateCsvImportNote();
});
});
// Resolve-Button // Resolve-Button
document.getElementById('csvResolveBtn')?.addEventListener('click', async () => { document.getElementById('csvResolveBtn')?.addEventListener('click', async () => {
const raw = document.getElementById('csvImportText').value; const raw = document.getElementById('csvImportText').value;
const upns = parseCsvUpns(raw);
if (upns.length === 0) { toast('Keine gültigen UPNs/E-Mails gefunden.', 'warn'); return; }
const btn = document.getElementById('csvResolveBtn'); const btn = document.getElementById('csvResolveBtn');
const stats = document.getElementById('csvResolveStats'); const stats = document.getElementById('csvResolveStats');
const dev = CsvImport.mode === 'devices';
const entries = dev ? parseCsvDevices(raw) : parseCsvUpns(raw);
if (entries.length === 0) {
toast(dev ? 'Keine Gerätenamen/Seriennummern gefunden.' : 'Keine gültigen UPNs/E-Mails gefunden.', 'warn');
return;
}
btn.disabled = true; btn.disabled = true;
btn.textContent = 'Löse auf…'; btn.textContent = 'Löse auf…';
stats.textContent = `${upns.length} Einträge werden aufgelöst…`; stats.textContent = `${entries.length} Einträge werden aufgelöst…`;
try { try {
const res = await api('/api/groups/resolve-upns', { method: 'POST', body: { upns } }); const res = dev
? await api('/api/groups/resolve-devices', { method: 'POST', body: { identifiers: entries } })
: await api('/api/groups/resolve-upns', { method: 'POST', body: { upns: entries } });
CsvImport.resolved = res.items || []; CsvImport.resolved = res.items || [];
renderCsvPreview(); renderCsvPreview();
stats.textContent = `${res.found} gefunden, ${res.notFound} nicht gefunden`; stats.textContent = `${res.found} gefunden, ${res.notFound} nicht gefunden`;
@@ -5666,7 +5721,7 @@ document.getElementById('csvResolveBtn')?.addEventListener('click', async () =>
stats.textContent = ''; stats.textContent = '';
} finally { } finally {
btn.disabled = false; btn.disabled = false;
btn.textContent = 'Benutzer auflösen'; btn.textContent = csvResolveLabel();
} }
}); });
@@ -5704,11 +5759,12 @@ function updateCsvImportNote() {
const note = document.getElementById('csvImportNote'); const note = document.getElementById('csvImportNote');
const importBtn = document.getElementById('csvImportBtn'); const importBtn = document.getElementById('csvImportBtn');
const found = CsvImport.resolved.filter(r => r.Found).length; const found = CsvImport.resolved.filter(r => r.Found).length;
const what = CsvImport.mode === 'devices' ? 'Geräte' : 'Benutzer';
if (!CsvImport.groupId) { if (!CsvImport.groupId) {
note.textContent = 'Gruppe links auswählen, dann Benutzer auflösen.'; note.textContent = `Gruppe links auswählen, dann ${what} auflösen.`;
importBtn.disabled = true; importBtn.disabled = true;
} else if (found === 0) { } else if (found === 0) {
note.textContent = `Gruppe: ${CsvImport.groupName} — keine aufgelösten Benutzer.`; note.textContent = `Gruppe: ${CsvImport.groupName} — keine aufgelösten ${what}.`;
importBtn.disabled = true; importBtn.disabled = true;
} else { } else {
note.textContent = `Gruppe: ${CsvImport.groupName}`; note.textContent = `Gruppe: ${CsvImport.groupName}`;
+6 -2
View File
@@ -342,7 +342,11 @@
<!-- Rechte Spalte: CSV-Import --> <!-- Rechte Spalte: CSV-Import -->
<div class="gex-right hidden" id="gexPaneImport"> <div class="gex-right hidden" id="gexPaneImport">
<div class="gex-section-title">UPNs einfügen oder CSV hochladen</div> <div class="csv-mode-toggle">
<label><input type="radio" name="csvImportMode" value="users" checked> Benutzer</label>
<label><input type="radio" name="csvImportMode" value="devices"> Geräte</label>
</div>
<div class="gex-section-title" id="csvImportTitle">UPNs einfügen oder CSV hochladen</div>
<div class="csv-import-input-row"> <div class="csv-import-input-row">
<textarea id="csvImportText" class="csv-import-textarea" placeholder="Eine UPN/E-Mail pro Zeile, z.B.&#10;max.mustermann@firma.de&#10;erika.muster@firma.de&#10;&#10;Oder erste Spalte einer CSV (Header wird erkannt)."></textarea> <textarea id="csvImportText" class="csv-import-textarea" placeholder="Eine UPN/E-Mail pro Zeile, z.B.&#10;max.mustermann@firma.de&#10;erika.muster@firma.de&#10;&#10;Oder erste Spalte einer CSV (Header wird erkannt)."></textarea>
<label class="csv-upload-label" title="CSV-Datei auswählen"> <label class="csv-upload-label" title="CSV-Datei auswählen">
@@ -364,7 +368,7 @@
</div> </div>
<div class="csv-preview-table-wrap"> <div class="csv-preview-table-wrap">
<table class="csv-preview-table"> <table class="csv-preview-table">
<thead><tr><th></th><th>UPN / E-Mail</th><th>Name</th><th>Status</th></tr></thead> <thead><tr><th></th><th id="csvPreviewColHead">UPN / E-Mail</th><th>Name</th><th>Status</th></tr></thead>
<tbody id="csvPreviewBody"></tbody> <tbody id="csvPreviewBody"></tbody>
</table> </table>
</div> </div>
+24
View File
@@ -5182,6 +5182,30 @@ body.read-only .app-row {
align-items: flex-start; align-items: flex-start;
} }
.csv-mode-toggle {
display: inline-flex;
gap: 2px;
margin-bottom: 8px;
background: var(--hairline-soft, rgba(255,255,255,.06));
border-radius: 7px;
padding: 2px;
}
.csv-mode-toggle label {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 3px 12px;
font-size: 12.5px;
border-radius: 5px;
cursor: pointer;
color: var(--text-dim, #999);
}
.csv-mode-toggle label:has(input:checked) {
background: var(--canvas);
color: var(--ink, inherit);
font-weight: 600;
}
.csv-mode-toggle input { accent-color: var(--accent, #60a5fa); }
.csv-import-textarea { .csv-import-textarea {
flex: 1; flex: 1;
height: 130px; height: 130px;