Export-HomelabDoc.ps1

<#PSScriptInfo
.VERSION 1.0.0
.GUID 529239a0-304e-5538-bd05-7b2e4a5c7c8c
.AUTHOR Torsten Weise
.COMPANYNAME powerscripting.de
.COPYRIGHT (c) 2026 Torsten Weise. MIT-Lizenz.
.TAGS Powerscripting German Homelab Linux PSEdition_Core Proxmox Docker PiHole AdGuard Documentation Markdown
.LICENSEURI https://powerscripting.de/skripte/files/LICENSE.txt
.PROJECTURI https://powerscripting.de/skripte/export-homelabdoc.html
.ICONURI https://powerscripting.de/assets/icon-192.png
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
Erste Veröffentlichung in der PowerShell Gallery.
.PRIVATEDATA
#>


<#
.SYNOPSIS
    Liest Proxmox VE, Docker-Hosts und den lokalen DNS (Pi-hole oder AdGuard Home) aus und schreibt eine Markdown-Dokumentation.
 
.DESCRIPTION
    Eine Homelab-Doku in Excel ist nach drei Wochen veraltet. Das Skript holt die Daten dort ab, wo sie
    ohnehin stimmen, und erzeugt daraus eine Markdown-Datei für Git, Wiki, Obsidian oder Gitea:
 
    - Proxmox VE (API-Token, nur lesend): Knoten mit CPU, RAM, Version, alle VMs und Container mit vCPU,
      RAM, Disk, Status, Tags und IP-Adressen (Container direkt, VMs über den QEMU Guest Agent),
      Speicher und Netzwerkbrücken.
    - Docker (lokal oder per SSH): alle Container je Host mit Image, Status, Ports und Compose-Projekt.
    - DNS: lokale Einträge aus Pi-hole 6 oder AdGuard Home. Die Namen werden den Gästen über die IP
      zugeordnet. Gäste ohne Namen und Namen ohne Ziel werden aufgelistet.
 
    Die Datei beginnt mit einer Übersicht und einem Mermaid-Diagramm, das Gitea, GitHub und Obsidian
    direkt anzeigen. Ein Abschnitt "Notizen" zwischen <!-- notizen --> und <!-- /notizen --> bleibt beim
    nächsten Lauf erhalten: dort stehen Dinge, die keine API kennt (Zugänge, Zweck, Ansprechpartner).
 
    Mit -SnapshotPath werden die Rohdaten zusätzlich als JSON gespeichert, mit -FromSnapshot lässt sich
    die Doku daraus ohne Netzwerkzugriff neu erzeugen.
 
.PARAMETER ProxmoxServer
    Adresse eines Proxmox-Knotens, z. B. pve.home.lan. Port 8006 wird ergänzt.
 
.PARAMETER ProxmoxTokenId
    Token-ID in der Form Benutzer@Realm!Tokenname, z. B. doku@pve!homelabdoc.
 
.PARAMETER ProxmoxTokenSecret
    Geheimnis des Tokens. Ohne Angabe wird aus der Umgebungsvariable PVE_TOKEN_SECRET gelesen oder gefragt.
 
.PARAMETER SkipCertificateCheck
    Selbst signierte Zertifikate von Proxmox, Pi-hole oder AdGuard akzeptieren.
 
.PARAMETER DockerHost
    Docker-Hosts: "local" für den lokalen Socket oder ssh://benutzer@host. Mehrere Werte als Liste oder
    mit Komma getrennt.
 
.PARAMETER DnsType
    None (Standard), PiHole (Version 6) oder AdGuard.
 
.PARAMETER DnsServer
    Adresse der DNS-Oberfläche, z. B. http://pihole.home.lan oder http://192.168.10.3:3000.
 
.PARAMETER DnsCredential
    Zugang zur DNS-Oberfläche. Pi-hole: nur das Kennwort zählt (Benutzername beliebig). Ohne Angabe wird gefragt.
 
.PARAMETER OutFile
    Zieldatei. Standard: homelab.md im aktuellen Ordner.
 
.PARAMETER Title
    Überschrift der Doku. Standard: Homelab.
 
.PARAMETER SnapshotPath
    Rohdaten zusätzlich als JSON speichern.
 
.PARAMETER FromSnapshot
    Doku aus einer gespeicherten JSON-Datei erzeugen, ohne Abfragen.
 
.EXAMPLE
    ./Export-HomelabDoc.ps1 -ProxmoxServer pve.home.lan -ProxmoxTokenId 'doku@pve!homelabdoc' -SkipCertificateCheck -DockerHost local, ssh://admin@docker01 -DnsType PiHole -DnsServer http://pihole.home.lan
 
    Liest alle drei Quellen und schreibt homelab.md.
 
.EXAMPLE
    ./Export-HomelabDoc.ps1 -ProxmoxServer 192.168.10.2 -ProxmoxTokenId 'doku@pve!homelabdoc' -OutFile /srv/git/homelab-doku/README.md -SnapshotPath /srv/git/homelab-doku/stand.json
 
    Schreibt die Doku direkt in ein Git-Repository. Danach per Cron committen, dann zeigt die Historie jede Änderung.
 
.NOTES
    Autor: Torsten Weise, powerscripting.de
    Läuft mit PowerShell 7 unter Linux, macOS und Windows. Für Docker muss die Docker-CLI installiert sein,
    für ssh:// ein SSH-Schlüssel ohne Rückfrage.
    Proxmox-Token: Datacenter > Berechtigungen > API Token, Rechtetrennung an, Rolle PVEAuditor auf Pfad /.
    Für IP-Adressen von VMs braucht das Token zusätzlich Zugriff auf den Guest Agent: in Proxmox VE 8 das
    Recht VM.Monitor, ab Proxmox VE 9 VM.GuestAgent.Audit. Dafür eine eigene Rolle mit VM.Audit, Sys.Audit,
    Datastore.Audit und dem Agent-Recht anlegen.
    Das Skript liest nur und ändert nichts.
#>

#Requires -Version 7.0
[CmdletBinding()]
param(
    [string] $ProxmoxServer,
    [string] $ProxmoxTokenId,
    [string] $ProxmoxTokenSecret,
    [switch] $SkipCertificateCheck,
    [string[]] $DockerHost,
    [ValidateSet('None', 'PiHole', 'AdGuard')] [string] $DnsType = 'None',
    [string] $DnsServer,
    [pscredential] $DnsCredential,
    [string] $OutFile = (Join-Path (Get-Location).Path 'homelab.md'),
    [string] $Title = 'Homelab',
    [string] $SnapshotPath,
    [string] $FromSnapshot
)

$ErrorActionPreference = 'Stop'
# -DockerHost 'a,b' aus Cron oder pwsh -File als Liste behandeln
$DockerHost = @($DockerHost | ForEach-Object { "$_" -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })

# ---------- Sammeln ----------

function Get-ProxmoxData {
    $secret = $ProxmoxTokenSecret
    if (-not $secret) { $secret = $env:PVE_TOKEN_SECRET }
    if (-not $secret) {
        $s = Read-Host -Prompt "Geheimnis für $ProxmoxTokenId" -AsSecureString
        $secret = [System.Net.NetworkCredential]::new('', $s).Password
    }
    $base = if ($ProxmoxServer -match ':\d+$') { "https://$ProxmoxServer/api2/json" } else { "https://${ProxmoxServer}:8006/api2/json" }
    $hdr = @{ Authorization = "PVEAPIToken=$ProxmoxTokenId=$secret" }
    $pve = { param($p) (Invoke-RestMethod -Uri "$base$p" -Headers $hdr -SkipCertificateCheck:$SkipCertificateCheck -TimeoutSec 30).data }

    $version = try { (& $pve '/version').version } catch { '' }
    $nodes = @(& $pve '/nodes' | Sort-Object node | ForEach-Object {
        [pscustomobject]@{ name = $_.node; status = $_.status; cpus = $_.maxcpu; memGB = [math]::Round($_.maxmem / 1GB, 1)
                    uptimeDays = [math]::Round($_.uptime / 86400, 1) }
    })
    $bridges = @()
    foreach ($n in $nodes | Where-Object status -eq 'online') {
        try {
            foreach ($b in @(& $pve "/nodes/$($n.name)/network") | Where-Object type -eq 'bridge') {
                $bridges += [pscustomobject]@{ node = $n.name; name = $b.iface; cidr = "$($b.cidr)"; vlanAware = [bool]$b.bridge_vlan_aware
                                        ports = "$($b.bridge_ports)"; comment = "$($b.comments)".Trim() }
            }
        } catch { Write-Warning "Netzwerk von $($n.name) nicht lesbar: $($_.Exception.Message)" }
    }
    $guests = @()
    foreach ($g in @(& $pve '/cluster/resources?type=vm') | Where-Object { -not $_.template } | Sort-Object vmid) {
        $ips = @()
        if ($g.status -eq 'running') {
            try {
                if ($g.type -eq 'lxc') {
                    foreach ($i in @(& $pve "/nodes/$($g.node)/lxc/$($g.vmid)/interfaces")) {
                        if ($i.name -ne 'lo' -and $i.inet) { $ips += ($i.inet -replace '/\d+$', '') }
                    }
                } else {
                    $r = & $pve "/nodes/$($g.node)/qemu/$($g.vmid)/agent/network-get-interfaces"
                    foreach ($i in @($r.result)) {
                        if ($i.name -match '^(lo|docker|br-|veth)') { continue }
                        foreach ($a in @($i.'ip-addresses')) {
                            if ($a.'ip-address-type' -eq 'ipv4' -and $a.'ip-address' -notmatch '^127\.') { $ips += $a.'ip-address' }
                        }
                    }
                }
            } catch { Write-Verbose "Keine IP für $($g.vmid): $($_.Exception.Message)" }
        }
        $guests += [pscustomobject]@{ id = [int]$g.vmid; name = $g.name; type = $(if ($g.type -eq 'lxc') { 'CT' } else { 'VM' }); node = $g.node
                               status = $g.status; cpus = $g.maxcpu; memGB = [math]::Round($g.maxmem / 1GB, 1)
                               diskGB = [math]::Round($g.maxdisk / 1GB, 0); tags = "$($g.tags)" -replace ';', ', '; ips = @($ips | Select-Object -Unique) }
    }
    $storage = @(& $pve '/cluster/resources?type=storage' | Sort-Object storage, node | ForEach-Object {
        [pscustomobject]@{ name = $_.storage; node = $_.node; type = $_.plugintype; shared = [bool]$_.shared
                    sizeGB = [math]::Round($_.maxdisk / 1GB, 0); usedPct = $(if ($_.maxdisk) { [math]::Round(100 * $_.disk / $_.maxdisk, [MidpointRounding]::AwayFromZero) } else { 0 }) }
    })
    # gemeinsame Speicher nur einmal
    $seen = @{}
    $storage = @($storage | Where-Object { if ($_.shared) { if ($seen[$_.name]) { $false } else { $seen[$_.name] = $true; $_.node = 'alle'; $true } } else { $true } })
    return [pscustomobject]@{ server = $ProxmoxServer; version = $version; nodes = $nodes; guests = $guests; storage = $storage; bridges = $bridges }
}

function Get-DockerData([string] $DockerHostName) {
    $hostArgs = @()
    if ($DockerHostName -and $DockerHostName -ne 'local') { $hostArgs = @('--host', $DockerHostName) }
    $label = if ($DockerHostName -eq 'local' -or -not $DockerHostName) { 'lokal' } else { $DockerHostName -replace '^ssh://([^@]+@)?', '' }
    $ver = (& docker @hostArgs version --format '{{.Server.Version}}' 2>$null)
    if ($LASTEXITCODE) { throw "Docker auf $label nicht erreichbar" }
    $lines = @(& docker @hostArgs ps --all --no-trunc --format '{{json .}}')
    if ($LASTEXITCODE) { throw "docker ps auf $label fehlgeschlagen" }
    $containers = foreach ($l in $lines | Where-Object { $_ }) {
        $c = $l | ConvertFrom-Json
        $labels = @{}
        foreach ($kv in "$($c.Labels)" -split ',') { $p = $kv -split '=', 2; if ($p.Count -eq 2) { $labels[$p[0]] = $p[1] } }
        $ports = @("$($c.Ports)" -split ',\s*' | Where-Object { $_ -match '->' } | ForEach-Object { ($_ -replace '^(0\.0\.0\.0|\[::\]|::):', '') } | Select-Object -Unique)
        [pscustomobject]@{ name = $c.Names; image = $c.Image; state = $c.State; status = $c.Status; ports = ($ports -join ', ')
                    project = "$($labels['com.docker.compose.project'])"; networks = "$($c.Networks)" }
    }
    return [pscustomobject]@{ host = $label; version = "$ver".Trim(); containers = @($containers | Sort-Object { $_.project }, { $_.name }) }
}

function Get-DnsData {
    $cred = $DnsCredential
    if (-not $cred) { $cred = Get-Credential -Message "Zugang für $DnsType ($DnsServer)" -UserName 'admin' }
    $base = $DnsServer.TrimEnd('/')
    $records = @()
    if ($DnsType -eq 'PiHole') {
        $body = @{ password = $cred.GetNetworkCredential().Password } | ConvertTo-Json
        $auth = Invoke-RestMethod -Method Post -Uri "$base/api/auth" -Body $body -ContentType 'application/json' -SkipCertificateCheck:$SkipCertificateCheck
        $hdr = @{ 'X-FTL-SID' = $auth.session.sid }
        try {
            $h = Invoke-RestMethod -Uri "$base/api/config/dns/hosts" -Headers $hdr -SkipCertificateCheck:$SkipCertificateCheck
            foreach ($line in @($h.config.dns.hosts)) {
                $p = "$line".Trim() -split '\s+'
                for ($i = 1; $i -lt $p.Count; $i++) { $records += [pscustomobject]@{ name = $p[$i]; type = 'A'; target = $p[0] } }
            }
            $c = Invoke-RestMethod -Uri "$base/api/config/dns/cnameRecords" -Headers $hdr -SkipCertificateCheck:$SkipCertificateCheck
            foreach ($line in @($c.config.dns.cnameRecords)) {
                $p = "$line".Split(',')
                if ($p.Count -ge 2) { $records += [pscustomobject]@{ name = $p[0].Trim(); type = 'CNAME'; target = $p[1].Trim() } }
            }
        } finally {
            try { Invoke-RestMethod -Method Delete -Uri "$base/api/auth" -Headers $hdr -SkipCertificateCheck:$SkipCertificateCheck | Out-Null } catch { Write-Verbose 'Abmelden fehlgeschlagen' }
        }
    } else {
        $pair = '{0}:{1}' -f $cred.UserName, $cred.GetNetworkCredential().Password
        $hdr = @{ Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($pair)) }
        foreach ($r in @(Invoke-RestMethod -Uri "$base/control/rewrite/list" -Headers $hdr -SkipCertificateCheck:$SkipCertificateCheck)) {
            $type = if ($r.answer -match '^\d{1,3}(\.\d{1,3}){3}$') { 'A' } elseif ($r.answer -match ':') { 'AAAA' } else { 'CNAME' }
            $records += [pscustomobject]@{ name = $r.domain; type = $type; target = $r.answer }
        }
    }
    return [pscustomobject]@{ type = $DnsType; server = $DnsServer; records = @($records | Sort-Object { $_.name }) }
}

if ($FromSnapshot) {
    $data = Get-Content -LiteralPath $FromSnapshot -Raw | ConvertFrom-Json
    Write-Host "Daten aus $FromSnapshot (Stand $($data.created))"
} else {
    if (-not $ProxmoxServer -and -not $DockerHost -and $DnsType -eq 'None') { throw 'Keine Quelle angegeben: -ProxmoxServer, -DockerHost oder -DnsType.' }
    $data = [ordered]@{ created = (Get-Date).ToString('yyyy-MM-ddTHH:mm:ss'); proxmox = $null; docker = @(); dns = $null }
    if ($ProxmoxServer) {
        if (-not $ProxmoxTokenId) { throw '-ProxmoxTokenId fehlt.' }
        $data.proxmox = Get-ProxmoxData
        Write-Host "Proxmox: $(@($data.proxmox.nodes).Count) Knoten, $(@($data.proxmox.guests).Count) Gäste"
    }
    foreach ($dh in $DockerHost) {
        try {
            $d = Get-DockerData $dh
            $data.docker += $d
            Write-Host "Docker $($d.host): $(@($d.containers).Count) Container"
        } catch { Write-Warning $_.Exception.Message }
    }
    if ($DnsType -ne 'None') {
        if (-not $DnsServer) { throw '-DnsServer fehlt.' }
        $data.dns = Get-DnsData
        Write-Host "DNS ($DnsType): $(@($data.dns.records).Count) Einträge"
    }
    if ($SnapshotPath) { $data | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $SnapshotPath -Encoding UTF8 }
}

# ---------- Markdown ----------

function C([object] $v) { return ("$v" -replace '\|', '\|' -replace '\r?\n', ' ').Trim() }
function Get-Id([string] $s) { return ($s -replace '[^A-Za-z0-9]', '_') }

# DNS-Namen je IP, Ziele von CNAMEs auflösen
$namesByIp = @{}
$aNames = @{}
$records = @()
if ($data.dns) { $records = @($data.dns.records) }
foreach ($r in $records | Where-Object { $_.type -in 'A', 'AAAA' }) {
    if (-not $namesByIp[$r.target]) { $namesByIp[$r.target] = @() }
    $namesByIp[$r.target] += $r.name
    $aNames[$r.name] = $r.target
}
$guestIps = @{}
$guests = @()
if ($data.proxmox) { $guests = @($data.proxmox.guests) }
foreach ($g in $guests) { foreach ($ip in @($g.ips)) { $guestIps[$ip] = $g.name } }

$md = New-Object System.Collections.Generic.List[string]
$md.Add("# $Title")
$md.Add('')
$created = if ($data.created -is [datetime]) { $data.created } else { [datetime]::Parse("$($data.created)", [Globalization.CultureInfo]::InvariantCulture) }
$md.Add("> Automatisch erzeugt am $($created.ToString('dd.MM.yyyy HH:mm')) mit Export-HomelabDoc.ps1. Änderungen nur im Abschnitt Notizen, der Rest wird beim nächsten Lauf überschrieben.")
$md.Add('')

$nCont = 0; foreach ($d in @($data.docker)) { $nCont += @($d.containers).Count }
$md.Add('## Übersicht')
$md.Add('')
$md.Add('| Bereich | Anzahl |')
$md.Add('| --- | ---: |')
if ($data.proxmox) {
    $running = @($guests | Where-Object status -eq 'running').Count
    $md.Add("| Proxmox-Knoten | $(@($data.proxmox.nodes).Count) |")
    $md.Add("| VMs | $(@($guests | Where-Object type -eq 'VM').Count) |")
    $md.Add("| Container (LXC) | $(@($guests | Where-Object type -eq 'CT').Count) |")
    $md.Add("| davon laufend | $running |")
    $cpu = ($guests | Where-Object status -eq 'running' | Measure-Object cpus -Sum).Sum
    $ram = ($guests | Where-Object status -eq 'running' | Measure-Object memGB -Sum).Sum
    $md.Add("| vCPU / RAM laufender Gäste | $cpu / $ram GB |")
}
if (@($data.docker).Count) { $md.Add("| Docker-Hosts / Container | $(@($data.docker).Count) / $nCont |") }
if ($data.dns) { $md.Add("| DNS-Einträge ($($data.dns.type)) | $($records.Count) |") }
$md.Add('')

# Diagramm
$md.Add('```mermaid')
$md.Add('flowchart LR')
if ($data.proxmox) {
    foreach ($n in @($data.proxmox.nodes)) {
        $nid = 'n_' + (Get-Id $n.name)
        $md.Add(" $nid[""$($n.name)<br/>$($n.cpus) CPU, $($n.memGB) GB""]")
        foreach ($g in $guests | Where-Object node -eq $n.name) {
            $gid = 'g' + $g.id
            $shape = if ($g.type -eq 'CT') { "([""$($g.id) $($g.name)""])" } else { "[""$($g.id) $($g.name)""]" }
            $md.Add(" $nid --> $gid$shape")
            if ($g.status -ne 'running') { $md.Add(" class $gid off") }
        }
    }
}
foreach ($d in @($data.docker)) {
    $did = 'd_' + (Get-Id $d.host)
    $md.Add(" $did{{""Docker $($d.host)<br/>$(@($d.containers).Count) Container""}}")
    foreach ($p in @($d.containers | Group-Object { if ($_.project) { $_.project } else { '(einzeln)' } })) {
        $md.Add(" $did --- $($did)_$(Get-Id $p.Name)[""$($p.Name): $($p.Count)""]")
    }
    # Docker-Host einem Gast zuordnen, wenn Name oder IP passt
    $match = $guests | Where-Object { $_.name -eq $d.host -or (@($_.ips) -contains $d.host) -or ($aNames[$d.host] -and @($_.ips) -contains $aNames[$d.host]) } | Select-Object -First 1
    if ($match) { $md.Add(" g$($match.id) -.- $did") }
}
$md.Add(' classDef off stroke-dasharray: 4 3,opacity:0.6')
$md.Add('```')
$md.Add('')

if ($data.proxmox) {
    $md.Add("## Proxmox VE$(if ($data.proxmox.version) { " $($data.proxmox.version)" })")
    $md.Add('')
    $md.Add('### Knoten')
    $md.Add('')
    $md.Add('| Knoten | Status | CPU | RAM | Laufzeit |')
    $md.Add('| --- | --- | ---: | ---: | ---: |')
    foreach ($n in @($data.proxmox.nodes)) { $md.Add("| $(C $n.name) | $(C $n.status) | $($n.cpus) | $($n.memGB) GB | $($n.uptimeDays) Tage |") }
    $md.Add('')
    $md.Add('### VMs und Container')
    $md.Add('')
    $md.Add('| ID | Name | Typ | Knoten | Status | vCPU | RAM | Disk | IP | DNS-Name | Tags |')
    $md.Add('| ---: | --- | --- | --- | --- | ---: | ---: | ---: | --- | --- | --- |')
    foreach ($g in $guests) {
        $dns = @(foreach ($ip in @($g.ips)) { $namesByIp[$ip] }) | Where-Object { $_ } | Select-Object -Unique
        $md.Add("| $($g.id) | $(C $g.name) | $($g.type) | $(C $g.node) | $(C $g.status) | $($g.cpus) | $($g.memGB) GB | $($g.diskGB) GB | $(C (@($g.ips) -join ', ')) | $(C ($dns -join ', ')) | $(C $g.tags) |")
    }
    $md.Add('')
    if (@($data.proxmox.storage).Count) {
        $md.Add('### Speicher')
        $md.Add('')
        $md.Add('| Speicher | Knoten | Typ | Größe | belegt |')
        $md.Add('| --- | --- | --- | ---: | ---: |')
        foreach ($s in @($data.proxmox.storage)) { $md.Add("| $(C $s.name) | $(C $s.node) | $(C $s.type) | $($s.sizeGB) GB | $($s.usedPct) % |") }
        $md.Add('')
    }
    if (@($data.proxmox.bridges).Count) {
        $md.Add('### Netzwerkbrücken')
        $md.Add('')
        $md.Add('| Knoten | Brücke | Adresse | VLAN-fähig | Ports | Kommentar |')
        $md.Add('| --- | --- | --- | --- | --- | --- |')
        foreach ($b in @($data.proxmox.bridges)) { $md.Add("| $(C $b.node) | $(C $b.name) | $(C $b.cidr) | $(if ($b.vlanAware) { 'ja' } else { 'nein' }) | $(C $b.ports) | $(C $b.comment) |") }
        $md.Add('')
    }
}

foreach ($d in @($data.docker)) {
    $md.Add("## Docker: $($d.host)$(if ($d.version) { " (Engine $($d.version))" })")
    $md.Add('')
    $md.Add('| Container | Compose-Projekt | Image | Status | Ports |')
    $md.Add('| --- | --- | --- | --- | --- |')
    foreach ($c in @($d.containers)) {
        $md.Add("| $(C $c.name) | $(C $c.project) | ``$(C $c.image)`` | $(C $c.status) | $(C $c.ports) |")
    }
    $md.Add('')
}

if ($data.dns) {
    $md.Add("## DNS ($($data.dns.type))")
    $md.Add('')
    $md.Add('| Name | Typ | Ziel | Gerät |')
    $md.Add('| --- | --- | --- | --- |')
    foreach ($r in $records) {
        $ip = if ($r.type -eq 'CNAME') { $aNames[$r.target] } else { $r.target }
        $dev = if ($ip -and $guestIps[$ip]) { $guestIps[$ip] } elseif ($r.type -eq 'CNAME' -and -not $aNames.ContainsKey($r.target)) { '(Ziel extern oder fehlt)' } else { '' }
        $md.Add("| $(C $r.name) | $($r.type) | $(C $r.target) | $(C $dev) |")
    }
    $md.Add('')
    $noName = @($guests | Where-Object { $_.status -eq 'running' -and @($_.ips).Count -and -not (@($_.ips) | Where-Object { $namesByIp[$_] }) })
    if ($noName.Count) {
        $md.Add('**Laufende Gäste ohne DNS-Namen:** ' + (($noName | ForEach-Object { "$($_.name) ($(@($_.ips)[0]))" }) -join ', '))
        $md.Add('')
    }
}

# Notizen aus der alten Datei übernehmen
$notes = "<!-- notizen -->`n## Notizen`n`nHier ist Platz für alles, was keine API kennt: Zweck der Dienste, Zugänge (nur Verweise auf den Passwortmanager), Ansprechpartner, offene Aufgaben.`n<!-- /notizen -->"
if (Test-Path -LiteralPath $OutFile) {
    $old = Get-Content -LiteralPath $OutFile -Raw
    $m = [regex]::Match($old, '(?s)<!-- notizen -->.*?<!-- /notizen -->')
    if ($m.Success) { $notes = $m.Value }
}
$md.Add($notes)
$md.Add('')

$dir = Split-Path -Parent $OutFile
if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
($md -join "`n") | Set-Content -LiteralPath $OutFile -Encoding UTF8 -NoNewline
Write-Host "Dokumentation geschrieben: $OutFile" -ForegroundColor Green
Get-Item -LiteralPath $OutFile