LunaFreigabe-QuittungEin Produkt von Luna · für SharePoint und OneDrive

Lese-Skript (nur lesen)

Das Skript liest für die von Ihnen ausgewählten Sites nur Metadaten von Dateien und Ordnern sowie deren Freigabeberechtigungen (Microsoft Graph, ausschließlich Get-Abfragen) und schreibt eine Datei freigabe-inventar.json auf Ihren PC. Keine Dateiinhalte, keine Freigabe-URLs, keine Änderungen, nichts wird an uns gesendet. Anmeldung über Ihre eigene App mit Zertifikat; E-Mail-Adressen werden lokal mit Ihrem Schlüssel pseudonymisiert.

Skript herunterladen Anleitung

<#
  Freigabe-Quittung - Lese-Skript (nur lesen, keine Aenderungen)
  Luna group L.L.C-FZ, Dubai - https://freigabe.lunafzai.com
  Version 1.0 (26.11.2026)

  Was es tut:   Liest fuer die von Ihnen ausgewaehlten SharePoint- und OneDrive-Sites die Metadaten von
                Dateien/Ordnern und deren Freigabeberechtigungen (Microsoft Graph, nur Get-Abfragen) und
                schreibt EINE Datei "freigabe-inventar.json" auf Ihren PC.
  Was es NICHT tut: keine Dateiinhalte, keine Freigabe-URLs, keine Aenderungen, nichts wird an uns gesendet.
                E-Mail-Adressen werden lokal mit einem Schluessel (HMAC-SHA256) pseudonymisiert; im JSON stehen
                nur Domaene + Pseudonym. Der Schluessel liegt in "freigabe-schluessel.txt" neben dem Skript und
                muss fuer Nachpruefungen gleich bleiben. Geben Sie ihn nicht weiter.

  Voraussetzungen: PowerShell 7, Modul Microsoft.Graph (Install-Module Microsoft.Graph -Scope CurrentUser).
                   Eine kundeneigene Single-Tenant-App mit Zertifikat und Anwendungsberechtigung Sites.Read.All
                   (Administratorzustimmung). Das ist eine mandantenweite Leseberechtigung; das Skript liest nur
                   die Sites aus Ihrer Liste.
  Optional:        -SharePointAdmin  (bestehende Sitzung Connect-SPOService; liest nur SharingCapability je Site)

  Aufruf:  .\freigabe-inventar.ps1 -TenantId <GUID> -ClientId <GUID> -Thumbprint <Zertifikat>
              -SitesCsv .\AktiveWebsites.csv -InterneDomaenen "firma.de","firma.onmicrosoft.com"
           (oder -Sites "https://firma.sharepoint.com/sites/Projekt","https://firma-my.sharepoint.com/personal/x")
#>
param(
  [Parameter(Mandatory)][string]$TenantId, [Parameter(Mandatory)][string]$ClientId, [Parameter(Mandatory)][string]$Thumbprint,
  [string]$SitesCsv = "", [string[]]$Sites = @(), [string[]]$InterneDomaenen = @(),
  [int]$MaxSites = 50, [int]$MaxObjekte = 20000, [switch]$SharePointAdmin, [string]$Ausgabe = ".\freigabe-inventar.json")
$ErrorActionPreference = "Stop"
$schl = Join-Path $PSScriptRoot "freigabe-schluessel.txt"
if (-not (Test-Path $schl)) { $b = New-Object byte[] 32; [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($b); [Convert]::ToBase64String($b) | Set-Content $schl -Encoding ascii }
$key = [Convert]::FromBase64String((Get-Content $schl -Raw).Trim())
$hm = New-Object Security.Cryptography.HMACSHA256 (,$key)
function Ref([string]$x) { ($hm.ComputeHash([Text.Encoding]::UTF8.GetBytes($x.Trim().ToLower())) | Select-Object -First 8 | ForEach-Object { $_.ToString("x2") }) -join "" }
$keyId = (([Security.Cryptography.SHA256]::Create().ComputeHash($key)) | Select-Object -First 4 | ForEach-Object { $_.ToString("x2") }) -join ""
$intern = @($InterneDomaenen | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })

# Site-Liste
$urls = @($Sites)
if ($SitesCsv) { $c = Import-Csv $SitesCsv -Delimiter ($(if ((Get-Content $SitesCsv -First 1) -match ';') { ';' } else { ',' }))
  $sp = ($c[0].PSObject.Properties.Name | Where-Object { $_ -match '^(Site ?URL|URL|Websit.?-?URL|Adresse)$' } | Select-Object -First 1)
  if (-not $sp) { throw "Spalte URL / Site URL im CSV nicht gefunden." }
  $urls += @($c | ForEach-Object { $_.$sp }) }
$urls = @($urls | ForEach-Object { "$_".Trim().TrimEnd('/') } | Where-Object { $_ -match '^https://' } | Select-Object -Unique)
if ($urls.Count -eq 0) { throw "Keine Site-URLs angegeben." }
if ($urls.Count -gt $MaxSites) { Write-Host "Liste enthaelt $($urls.Count) Sites. Bitte auswaehlen (max. $MaxSites):" -ForegroundColor Yellow
  if (Get-Command Out-GridView -ErrorAction SilentlyContinue) { $urls = @($urls | Out-GridView -Title "Sites auswaehlen (max. $MaxSites)" -PassThru) }
  if ($urls.Count -gt $MaxSites) { throw "Mehr als $MaxSites Sites ausgewaehlt. Bitte mit -Sites eine kleinere Liste angeben." } }

Write-Host "Anmeldung (App-only, Zertifikat, nur Lesen) ..." -ForegroundColor Cyan
Connect-MgGraph -TenantId $TenantId -ClientId $ClientId -CertificateThumbprint $Thumbprint -NoWelcome
$ctx = Get-MgContext
if ($ctx.TenantId -ne $TenantId -or $ctx.AuthType -ne "AppOnly") { throw "Unerwarteter Anmeldekontext ($($ctx.TenantId), $($ctx.AuthType)). Abbruch." }

function Prinz($idset, [string]$art) {
  # liefert @{ ref; domain; typ } typ = intern | extern | unbekannt | gruppe
  if (-not $idset) { return $null }
  $u = $idset.User; $g = $idset.Group; $su = $idset.SiteUser; $sg = $idset.SiteGroup
  $mail = $null
  if ($su -and $su.Email) { $mail = $su.Email } elseif ($su -and $su.LoginName -match '\|([^|#]+@[^|#]+)$') { $mail = $Matches[1] }
  if (-not $mail -and $u -and $u.AdditionalProperties -and $u.AdditionalProperties.email) { $mail = $u.AdditionalProperties.email }
  if (-not $mail -and $u -and $u.Email) { $mail = $u.Email }
  if ($mail) { $d = ($mail -split '@')[-1].ToLower(); $t = if ($intern.Count -eq 0) { "unbekannt" } elseif ($intern -contains $d) { "intern" } else { "extern" }
    return @{ ref = (Ref $mail); domain = $d; typ = $t } }
  if ($sg) { return @{ ref = "sg-" + (Ref ([string]$sg.Id)); domain = ""; typ = "sitegruppe" } }
  if ($g) { return @{ ref = "g-" + (Ref ([string]$g.Id)); domain = ""; typ = "gruppe" } }
  if ($u -and $u.Id) { return @{ ref = "u-" + (Ref ([string]$u.Id)); domain = ""; typ = "unbekannt" } }
  return @{ ref = ""; domain = ""; typ = "unbekannt" }
}

$R = [ordered]@{ format = "luna-freigabe-inventar"; schemaVersion = 1; collectorVersion = "1.0"; snapshotAtUtc = (Get-Date).ToUniversalTime().ToString("o")
  tenantId = $TenantId; keyId = $keyId; internalDomains = $intern; maskingMode = "hmac-sha256-64"; sites = @() }
$gesamt = 0
foreach ($url in $urls) {
  $S = [ordered]@{ siteUrl = $url; siteId = ""; sourceKind = $(if ($url -match '-my\.sharepoint\.com/personal/') { "OneDrive" } else { "SharePoint" }); sharingCapability = ""; sharingCapabilitySource = ""; status = "ok"; fehler = @(); drives = @(); permissions = @() }
  Write-Host "-> $url" -ForegroundColor Cyan
  try {
    $uri = [Uri]$url; $site = Get-MgSite -SiteId ("{0}:{1}" -f $uri.Host, $(if ($uri.AbsolutePath -eq '/') { '/' } else { $uri.AbsolutePath }))
    $S.siteId = $site.Id
    if ($SharePointAdmin) { try { $s2 = Get-SPOSite -Identity $url -Detailed; $S.sharingCapability = [string]$s2.SharingCapability; $S.sharingCapabilitySource = "Get-SPOSite" } catch { $S.fehler += "SharingCapability: $($_.Exception.Message)" } }
    foreach ($dr in @(Get-MgSiteDrive -SiteId $site.Id -All)) {
      $D = [ordered]@{ driveId = $dr.Id; name = $dr.Name; traversalStatus = "vollstaendig"; attemptedItems = 0; readItems = 0; errors = 0 }
      $root = Get-MgDriveRoot -DriveId $dr.Id
      $stapel = New-Object System.Collections.Stack; $stapel.Push(@{ id = $root.Id; pfad = "/"; ordner = $true })
      while ($stapel.Count -gt 0) {
        $it = $stapel.Pop()
        if ($gesamt -ge $MaxObjekte) { $D.traversalStatus = "abgebrochen (Objektlimit)"; break }
        $D.attemptedItems++; $gesamt++
        try {
          foreach ($p in @(Get-MgDriveItemPermission -DriveId $dr.Id -DriveItemId $it.id -All)) {
            $scope = $(if ($p.Link -and $p.Link.Scope) { switch ($p.Link.Scope) { "anonymous" { "Anyone" } "organization" { "Organization" } "users" { "SpecificPeople" } default { "Other" } } } else { "Direct" })
            $pr = @(); foreach ($x in @($p.GrantedToIdentitiesV2) + @($p.GrantedToV2)) { $q = Prinz $x; if ($q) { $pr += $q } }
            if ($p.Invitation -and $p.Invitation.Email) { $d = ($p.Invitation.Email -split '@')[-1].ToLower(); $pr += @{ ref = (Ref $p.Invitation.Email); domain = $d; typ = $(if ($intern.Count -eq 0) { "unbekannt" } elseif ($intern -contains $d) { "intern" } else { "extern" }) } }
            $pr = @($pr | Where-Object { $_.typ -ne "sitegruppe" })
            $relevant = ($scope -eq "Anyone") -or (@($pr | Where-Object { $_.typ -ne "intern" }).Count -gt 0)
            if (-not $relevant) { continue }
            $S.permissions += [ordered]@{ driveId = $dr.Id; itemId = $it.id; itemPath = $it.pfad; isFolder = $it.ordner; permissionId = $p.Id; scope = $scope
              roles = @($p.Roles); principalRefs = @($pr); expirationDateTime = $(if ($p.ExpirationDateTime) { $p.ExpirationDateTime.ToUniversalTime().ToString("o") } else { $null })
              expiryStatus = $(if ($p.ExpirationDateTime) { "belegt" } else { "nicht belegt" }); inherited = [bool]$p.InheritedFrom }
          }
          if ($it.ordner) { foreach ($k in @(Get-MgDriveItemChild -DriveId $dr.Id -DriveItemId $it.id -All -Property "id,name,folder")) {
              $stapel.Push(@{ id = $k.Id; pfad = ($it.pfad.TrimEnd('/') + "/" + $k.Name); ordner = [bool]$k.Folder }) } }
          $D.readItems++
        } catch { $D.errors++; if ($D.errors -le 5) { $S.fehler += "$($dr.Name)$($it.pfad): $($_.Exception.Message)" } }
      }
      if ($D.errors -gt 0 -and $D.traversalStatus -eq "vollstaendig") { $D.traversalStatus = "teilweise" }
      $S.drives += $D
      Write-Host ("   {0}: {1} Objekte, {2} Fehler" -f $dr.Name, $D.readItems, $D.errors)
    }
    if (@($S.drives | Where-Object { $_.traversalStatus -ne "vollstaendig" }).Count -gt 0) { $S.status = "teilweise" }
  } catch { $S.status = "fehler"; $S.fehler += $_.Exception.Message; Write-Host "   nicht lesbar: $($_.Exception.Message)" -ForegroundColor Yellow }
  $R.sites += $S
}
$R | ConvertTo-Json -Depth 8 | Set-Content -Path $Ausgabe -Encoding utf8
Disconnect-MgGraph | Out-Null
Write-Host "Fertig: $Ausgabe ($gesamt Objekte). Datei im Browser auf https://freigabe.lunafzai.com auswaehlen." -ForegroundColor Green