Hive BDC: E-Rechnung für Dynamics AX und D365 F&O

Balsoft Data Connector: E-Rechnungen senden und empfangen (XRechnung, ZUGFeRD) für Microsoft Dynamics 365 F&O, AX 2012 und AX 2009.

Installation · ein Tag

  1. Setup herunterladen (130 MB, von Balsoft signiert)
  2. Dienst und Dashboard installieren
  3. Dynamics-Modul durch Balsoft eingespielt
  4. Testbeleg als XRechnung senden
  5. Go-live

D365 F&O · AX 2012 · AX 2009

Hive BDC

Ausgangs- und Eingangsrechnungen in einem Ablauf

Hive BDC macht aus einer gebuchten Verkaufsrechnung eine E-Rechnung im Format XRechnung oder ZUGFeRD. Auftragsbestätigungen, Angebote, Mahnungen, Bestellungen und Zahlungsavise gehen als das PDF hinaus, das Ihr ERP druckt. Jeder Beleg kann per Mail an den Empfänger gehen und in SharePoint, ShareFlex, DocuWare oder Ihrem vorhandenen DMS abgelegt werden. In die andere Richtung nimmt Hive BDC die E-Rechnungen Ihrer Lieferanten aus einem Postfach, einem Ordner oder Ihrem DMS (zum Beispiel SharePoint) und über Peppol an, liest XRechnung und ZUGFeRD in CII und UBL, prüft sie nach EN 16931 und gleicht die Summen ab. Hive BDC legt daraus in Dynamics eine ausstehende Kreditorenrechnung, eine Bestellrechnung oder ein Rechnungsjournal an.

Ein Windows-Dienst erledigt die Arbeit im Hintergrund, ein Dashboard zeigt, was hinausgegangen und was hereingekommen ist, und enthält die Einstellungen. Auf ERP-Seite gehört ein Hive-BDC-Modul für Dynamics dazu, Balsoft installiert es für Sie.

Unterstützte Systeme

Standards

XRechnung 3.0.2ZUGFeRD 2.5.2EN 16931

So arbeitet Hive BDC

Zwei Richtungen, ein Produkt. Ausgangsrechnungen verlassen Dynamics als XRechnung oder ZUGFeRD, eingehende E-Rechnungen landen als Kreditorenrechnung in Dynamics. Beides läuft als Batch-Job, niemand muss eine Datei anfassen.

Ausgangsrechnungen (AR): So geht eine E-Rechnung hinaus, aus Dynamics AX 2009, AX 2012 und D365 F&O on-premises (LBD)

Von der gebuchten Rechnung in Dynamics bis ins Postfach des Kunden und in Ihr Archiv, ohne dass jemand eingreifen muss.

Ausgangsrechnungen (AR)EN 16931 XRechnung 3.0.2 ZUGFeRD 2.5.2
DynamicsDynamicsAuftragSO-10234BuchenVerkaufsrechnungMuster GmbH1.190,00 €AX 2012AX 2009ERP-ModulExportstapelHive BDCHive BDCDashboardConnectedSERVICERunningv1.15.1LICENSEValidEXPORTS6TodayRECENT EXPORTSDocument IDTypeFormat7000001234SalesInvoicexrechnungAB0004711SalesConfirmationpdfAN0000815SalesQuotationpdfHive BDC DashboardPostfach des KundenMicrosoft 365DMSAblageSharePointShareFlexDocuWared.velopM-FilesELOenaiowindreamDoxisnscaleWeitere DMSVerkaufsrechnungINV-10234Muster GmbH1.190,00 €E-INVOICE · EN 16931<Invoice></Invoice>
01

Die Rechnung wird in Dynamics gebucht

Was es leistet

Ausgangsrechnungen (AR): XRechnung und ZUGFeRD

Verkaufsrechnungen werden zu E-Rechnungen nach EN 16931, vor dem Versand geprüft, inklusive Gutschriften, Skonto und Daten für die Zentralregulierung.

Eingangsrechnungen (AP)

E-Rechnungen Ihrer Lieferanten kommen per Mail, Ordner, DMS (zum Beispiel SharePoint) oder Peppol an. Hive BDC liest XRechnung und ZUGFeRD (CII und UBL), prüft sie und legt eine ausstehende Kreditorenrechnung, eine Bestellrechnung oder ein Rechnungsjournal an.

PDF-Belege

Auftragsbestätigungen, Angebote, Mahnungen, Bestellungen und Zahlungsavise gehen als das PDF hinaus, das Ihr ERP druckt.

Kleinere PDFs

Mit Compress PDF wird jede PDF einmal kleiner, bevor sie hinausgeht: Schriften behalten nur die verwendeten Zeichen, und Bilder mit mehr als 300 ppi werden auf 200 ppi verkleinert. Die Seiten sehen gleich aus. Eine ZUGFeRD-Rechnung aus AX 2009 wurde von 945 KB auf 138 KB kleiner.

Versand über Microsoft 365

Empfänger, Betreff und Text kommen aus dem ERP. Die Belege gehen aus Ihrem eigenen Postfach und bleiben in dessen gesendeten Elementen.

SharePoint, DocuWare und andere DMS

Belege gehen direkt in eine SharePoint-Bibliothek, auch mit ShareFlex, mit Metadatenspalten aus dem Beleg. DocuWare, d.velop, ELO, M-Files, enaio, windream und andere DMS lesen die fertigen Dateien aus dem Ausgabeordner (lokal, Netzwerkfreigabe oder synchronisierter Cloud-Ordner) mit ihrem Ordnerimport oder ihrem eigenen Connector.

Läuft auf Ihren Servern

Belegdaten gehen nie an Balsoft oder einen anderen Dienst, nur an die Empfänger und die SharePoint-Site, die Sie einrichten.

Testsysteme bleiben intern

Belege aus einem Test- oder Entwicklungssystem gehen an Ihre Testempfänger, nie an Kunden oder Lieferanten.

E-Rechnungsformate

Welches Format ein Kunde erhält, legen Sie im ERP fest, pro Rechnung: XRechnung als XML oder ZUGFeRD als PDF mit demselben XML darin. Beide folgen der EN 16931 und werden vor dem Versand geprüft.

XRechnung

3.0.2

Für die öffentliche Hand (mit Leitweg-ID) und alle Empfänger, die XML verarbeiten.

Format
XML, Syntax UN/CEFACT CII
Norm
EN 16931 mit der deutschen CIUS
Spezifikations-ID
urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0
Datei
Eine XML-Datei pro Rechnung
Geprüft mit
KoSIT-Validator 1.6.3, Konfiguration 2026-08-31 (XRechnung 3.0.2)

ZUGFeRD

2.5.2 / Factur-X 1.09.2

Für Empfänger, die ein lesbares PDF und maschinenlesbare Daten in einer Datei wollen.

Format
PDF/A-3b mit angehängtem XML
Profil
XRECHNUNG: dasselbe XRechnung-3.0.2-XML wie links
Im PDF
xrechnung.xml, Factur-X-XMP-Metadaten, sRGB-Output-Intent, eingebettete Schriften
Quelle
Das Rechnungs-PDF, das Ihr ERP druckt
Geprüft mit
Mustang 2.26 mit den Regeln von ZUGFeRD 2.5.2 und der PDF/A-3-Prüfung (veraPDF), KoSIT-Validator für das XML

Was die E-Rechnung enthält

  • Rechnungen, Gutschriften und Rechnungskorrekturen (Typcodes 380, 381 und 384)
  • Leitweg-ID für öffentliche Auftraggeber (BT-10)
  • Bestell-, Vertrags-, Projekt-, Lieferschein- und Vergabereferenzen (BT-11 bis BT-17)
  • Skonto, auch mehrstufig, in der maschinenlesbaren XRechnung-Form
  • Umsatzsteuer je Satz und Kategorie, also 19 % und 7 % auf einer Rechnung
  • Bankverbindung, Lieferdatum und Verwendungszweck
  • Artikelnummern, GTIN und Ursprungsland je Position
  • Kennungen für Zentralregulierer, zum Beispiel für die Aktivbank

Jede Rechnung durchläuft vor dem Schreiben eine Prüfung der Geschäftsregeln aus EN 16931 und XRechnung. Jeder Befund wird mit seiner offiziellen Regel-ID protokolliert, zum Beispiel BR-DE-15, damit fehlende Daten im ERP ergänzt werden können.

Alle anderen Belege (Auftragsbestätigungen, Angebote, Mahnungen, Bestellungen, Zahlungsavise) gehen als das PDF hinaus, das Ihr ERP druckt.

Hive BDC folgt neuen Versionen beider Standards. XRechnung 4.0 auf Basis der überarbeiteten EN 16931 wird für Frühjahr 2027 erwartet; XRechnung 3.0.2 gilt mindestens bis zum 31. Juli 2027. Updates kommen über das Dashboard.

E-Rechnung nach Dynamics-Version

Lizenz und Quellcode

Lizenz

10.000 EUR

pro Jahr, zzgl. MwSt.

  • Support und Updates inklusive
  • Lizenzdatei für 12 Monate, mit jeder Jahresrechnung kommt eine neue
  • Einspielen über das Dashboard, ohne Neustart
Lizenzbedingungen lesen

Quellcode

Der vollständige Quellcode von Hive BDC ist auf GitHub öffentlich einsehbar. Ihre IT, Prüfer und Partner sehen genau, was auf Ihrem Server läuft, bevor Sie installieren.

Source Available, nicht Open Source: Betrieb, Kopie oder Änderung der Software erfordern eine Lizenz von Balsoft.

Quellcode auf GitHub ansehen

Systemvoraussetzungen

Was Sie für Installation und Betrieb von Hive BDC brauchen. Ihr Balsoft-Berater geht es mit Ihnen durch und installiert den ERP-Teil.

Dynamics

  • Dynamics 365 Finance & Supply Chain Management in der Cloud.
  • Das Hive-BDC-Modul im ERP, geliefert und installiert von Balsoft.
  • Ein Batchserver, der die Hive-BDC-Exportaufträge ausführt.

Azure

  • Ein Azure Service Bus Namespace oder ein Storage-Konto in Ihrem Azure-Abonnement; darüber tauschen Dynamics 365 und Hive BDC die Belege aus.
  • Balsoft richtet die Verbindung ein; die Zugangsdaten liegen in Ihrem Key Vault.

Microsoft 365 (für den Mailversand)

  • Mail: eine App-Registrierung in Entra ID mit Mail.Send und das Absenderpostfach. Balsoft stellt ein Skript bereit, das sie anlegt und auf dieses Postfach beschränkt.
  • HTTPS-Zugriff vom Server auf login.microsoftonline.com und graph.microsoft.com.

Lizenz

  • Eine Lizenzdatei von Balsoft, gebunden an Ihren Microsoft-365-Mandanten. Sie schaltet E-Rechnungen, PDF-Belege und SharePoint frei.
  • Das Dashboard warnt vor dem Ablauf. Belege gehen nie verloren: Ohne gültige Lizenz warten sie im Exportordner.

SharePoint oder ein anderes DMSOptional

  • Nur wenn Belege zusätzlich abgelegt werden sollen. Hive BDC läuft auch ohne.
  • SharePoint: eine App-Registrierung mit Sites.ReadWrite.All oder Sites.Selected für die Ziel-Site.
  • DocuWare, d.velop, ELO, M-Files und andere DMS: Hive BDC schreibt die fertigen Dateien in einen Ausgabeordner (lokal, Netzwerkfreigabe oder ein auf den Server synchronisierter Cloud-Ordner), und das DMS liest sie mit seinem Ordnerimport oder seinem eigenen Connector.

Downloads

Version 1.15.1, veröffentlicht am 27. November 2026, etwa 130 MB, Windows x64

Hive BDC Setup

Version 1.15.1, veröffentlicht am 27. November 2026, etwa 130 MB, Windows x64

Eine Datei mit allem, was Sie installieren: Windows-Dienst und Dashboard. Die Datei ist von der Balsoft GmbH signiert; Windows zeigt Balsoft GmbH als Herausgeber. Installierte Systeme aktualisieren sich über das Dashboard.

Setup 1.15.1 herunterladen

SHA-256-Prüfsumme:
d059b0a5ce15a657a9b4b5537ac03cf7496b685b950e2f9d896d761393320800

Installations- und Benutzerhandbücher

PDF, auf Deutsch. Die englische Fassung finden Sie auf der englischen Seite.

  • Microsoft Dynamics AX 2012PDF, 5,8 MB
  • Dynamics 365 Finance and OperationsFolgt in Kürze
  • Microsoft Dynamics AX 2009PDF, 6,3 MB

Einrichtung in Microsoft 365 für Mail und SharePoint

Für Ihre IT-Administration. Nur nötig, wenn Hive BDC Belege per Mail versendet oder in SharePoint ablegt.

Setup-Anleitung

Hive BDC meldet sich mit zwei App-Registrierungen in Ihrem Mandanten bei Microsoft 365 an: Die eine darf nur als ein Postfach senden, die andere nur in die SharePoint-Sites schreiben, die Sie nennen. Zwei PowerShell-Skripte richten beide in wenigen Minuten in Azure Cloud Shell ein. Sie fragen, bevor sie etwas ändern, und erzeugen oder speichern keine geheimen Schlüssel. Das Handbuch führt durch jeden Schritt.

Einrichtungshandbuch, PDF, 0,4 MB

In Azure Cloud Shell ausführen

Jede App wird in zwei Schritten in Azure Cloud Shell (PowerShell) Ihres Mandanten eingerichtet: zuerst die App-Registrierung, dann ihre Berechtigungen. Die Schritte können verschiedene Administratoren ausführen. Jedes Skript zeigt den Mandanten und fragt, bevor es etwas ändert; mit -WhatIf gibt es einen Probelauf.

Der Quelltext beider Skripte ist auch öffentlich im Hive-BDC-Repository auf GitHub.

1App-Registrierung anlegen

Legt „Hive BDC SharePoint“ ohne Berechtigungen an und gibt die Client-ID aus. Braucht die Rolle Anwendungsadministrator.

Azure Cloud Shell
Invoke-WebRequest https://balsoft.de/downloads/hive-bdc/New-HiveBDCSharePointApp.ps1 -OutFile New-HiveBDCSharePointApp.ps1./New-HiveBDCSharePointApp.ps1
New-HiveBDCSharePointApp.ps1
<#.SYNOPSIS    Step 1 of 2 for SharePoint: creates the app registration "Hive BDC SharePoint", without any permission..DESCRIPTION    Run in Azure Cloud Shell (PowerShell). It shows the tenant and asks first, skips the app    if it already exists, creates its service principal, and prints the IDs plus the    command for step 2, Grant-HiveBDCSharePointAccess.ps1, which assigns Sites.Selected and the site access.    Role: Application Developer or Application Administrator. No client secret is    created; the script prints how. -WhatIf shows the plan only..EXAMPLE    ./New-HiveBDCSharePointApp.ps1#>#Requires -Version 5.1[CmdletBinding(SupportsShouldProcess = $true)]param(    [ValidateLength(3, 120)]    [string] $AppName = 'Hive BDC SharePoint',    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]    [string] $TenantId,    # Do not ask before changing the tenant.    [switch] $Force)$ErrorActionPreference = 'Stop'function Write-Step { param([string] $Text) Write-Host "`n== $Text" -ForegroundColor Cyan }function Write-Ok { param([string] $Text) Write-Host "   [ok]   $Text" -ForegroundColor Green }function Write-Skip { param([string] $Text) Write-Host "   [have] $Text" -ForegroundColor DarkGray }function Write-Note { param([string] $Text) Write-Host "   $Text" -ForegroundColor Gray }# Only Cloud Shell has no browser to sign in with; there a device code is the way in.# Elsewhere the browser is used, because many tenants block sign-in by code.$isCloudShell = [bool]$env:ACC_CLOUD -or ("$env:AZUREPS_HOST_ENVIRONMENT" -like '*cloud-shell*')$useDeviceCode = $isCloudShell# Runs az and returns its JSON output; a failed command stops the script.function Invoke-Az {    $output = & az @args --only-show-errors --output json    if ($LASTEXITCODE -ne 0) { throw "'az $($args[0]) $($args[1])' failed (exit code $LASTEXITCODE), see above." }    $text = ($output | Out-String).Trim()    if (-not $text) { return }    $parsed = $text | ConvertFrom-Json    return $parsed   # return, not the pipeline, so a JSON array arrives as its items}function Get-AzCliAccount {    $ErrorActionPreference = 'Continue'   # 'not signed in' arrives on stderr    $text = (& az account show --output json 2>$null | Out-String).Trim()    if ($LASTEXITCODE -eq 0 -and $text) { return $text | ConvertFrom-Json }}if ($WhatIfPreference) { Write-Host 'DRY RUN - nothing will be changed.' -ForegroundColor Yellow }# -- 1. sign-in -----------------------------------------------------------------------Write-Step '1/2 Sign-in'if (-not (Get-Command az -ErrorAction SilentlyContinue)) {    throw 'Azure CLI (az) was not found. Run this script in Azure Cloud Shell (PowerShell).'}$account = Get-AzCliAccountif (-not $account -or ($TenantId -and $account.tenantId -ne $TenantId)) {    $login = @('login', '--allow-no-subscriptions', '--only-show-errors', '--output', 'none')    if ($TenantId) { $login += @('--tenant', $TenantId) }    if ($useDeviceCode) { $login += '--use-device-code' }    & az @login    if ($LASTEXITCODE -ne 0) { throw 'az login failed.' }    $account = Get-AzCliAccount}$tenantId = $account.tenantId$tenantName = (@((Invoke-Az rest --method GET --url 'https://graph.microsoft.com/v1.0/organization?$select=displayName').value) |    Select-Object -First 1).displayNameWrite-Note "tenant:  $tenantName ($tenantId)"Write-Note "account: $($account.user.name)"if (-not $Force -and -not $WhatIfPreference) {    $answer = Read-Host "   Create '$AppName' in '$tenantName'? (y/n)"    if ($answer -notmatch '^(y|yes|j|ja)$') { Write-Note 'Stopped. Nothing was changed.'; return }}# -- 2. app registration and service principal ----------------------------------------Write-Step "2/2 App registration '$AppName'"$apps = @(Invoke-Az ad app list --display-name $AppName | Where-Object { $_.displayName -eq $AppName })if ($apps.Count -gt 1) { throw "There are $($apps.Count) app registrations named '$AppName'. Remove the extra ones, or use -AppName." }$reg = $apps | Select-Object -First 1if ($reg) { Write-Skip "app registration exists (appId $($reg.appId))" }elseif ($PSCmdlet.ShouldProcess($AppName, 'Create the app registration')) {    $reg = Invoke-Az ad app create --display-name $AppName --sign-in-audience AzureADMyOrg    Write-Ok "created the app registration (appId $($reg.appId))"}if (-not $reg) { Write-Note 'Dry run ends here: the app does not exist yet.'; return }$appId = $reg.appId$sp = Invoke-Az ad sp list --spn $appId | Select-Object -First 1if ($sp) { Write-Skip "service principal exists ($($sp.id))" }elseif ($PSCmdlet.ShouldProcess($appId, 'Create the service principal')) {    for ($attempt = 1; -not $sp; $attempt++) {   # a new app needs a few seconds to replicate        try { $sp = Invoke-Az ad sp create --id $appId }        catch { if ($attempt -ge 4) { throw }; Start-Sleep -Seconds 10 }    }    Write-Ok "created the service principal ($($sp.id))"}# -- next -----------------------------------------------------------------------------$grant = "./Grant-HiveBDCSharePointAccess.ps1 -AppId $appId -SiteUrl https://<tenant>.sharepoint.com/sites/<site>"Write-Host "`nDONE, the app has no permissions yet" -ForegroundColor YellowWrite-Host "  Tenant ID  $tenantId"Write-Host "  Client ID  $appId"Write-Note ''Write-Note 'Step 2, assign the permissions:'Write-Note "  $grant"Write-Note 'Client secret (shown once, enter it straight into the Hive BDC dashboard):'Write-Note "  az ad app credential reset --id $appId --append --display-name HiveBDC --years 2 --query password -o tsv"
2Berechtigungen zuweisen

Erteilt Sites.Selected mit Administratorzustimmung und gibt der App Schreibzugriff auf die genannten Sites und auf keine andere. Verwenden Sie die Client-ID aus Schritt 1. Braucht Globaler Administrator (oder Administrator für privilegierte Rollen) und SharePoint-Administrator.

Azure Cloud Shell
Invoke-WebRequest https://balsoft.de/downloads/hive-bdc/Grant-HiveBDCSharePointAccess.ps1 -OutFile Grant-HiveBDCSharePointAccess.ps1./Grant-HiveBDCSharePointAccess.ps1 -AppId <client-id> -SiteUrl https://contoso.sharepoint.com/sites/Invoices
Grant-HiveBDCSharePointAccess.ps1
<#.SYNOPSIS    Step 2 of 2 for SharePoint: gives the Hive BDC SharePoint app write access to the sites    you name, and to no other..DESCRIPTION    Run in Azure Cloud Shell (PowerShell) after New-HiveBDCSharePointApp.ps1.    Steps, each skipped when already in place:      1. Azure CLI: show the tenant and the app, and ask before changing anything.      2. Entra ID: Microsoft Graph application permission Sites.Selected with admin consent.         Sites.Selected alone opens no site at all.      3. SharePoint: write access on each -SiteUrl. This needs the delegated permission         Sites.FullControl.All, which an Azure CLI sign-in does not carry, so it signs in         once more through Microsoft's public client "Microsoft Graph Command Line Tools"         (the one Connect-MgGraph uses): in a browser on a PC, by code in Cloud Shell. No         PowerShell module needed. If the tenant blocks sign-in by code, run this script on         your own computer instead of Cloud Shell.    -AllSites grants Sites.ReadWrite.All (every site) instead and skips step 3.    Roles: Privileged Role Administrator or Global Administrator for the consent, and    SharePoint Administrator who is a member of each site. -WhatIf shows the plan only.    Another site later: run it again with that site..EXAMPLE    ./Grant-HiveBDCSharePointAccess.ps1 -AppId 11111111-2222-3333-4444-555555555555 -SiteUrl https://contoso.sharepoint.com/sites/Invoices#>#Requires -Version 5.1[CmdletBinding(SupportsShouldProcess = $true)]param(    # Application (client) ID printed by New-HiveBDCSharePointApp.ps1.    [Parameter(Mandatory = $true)]    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]    [string] $AppId,    # Sites Hive BDC uploads to; a library or folder URL is reduced to its site.    [ValidatePattern('^https://[^/\s]+\.sharepoint\.(com|us|de|cn)(/\S*)?$')]    [string[]] $SiteUrl = @(),    [switch] $AllSites,    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]    [string] $TenantId,    # Do not ask before changing the tenant.    [switch] $Force)$ErrorActionPreference = 'Stop'if (-not $AllSites -and $SiteUrl.Count -eq 0) { throw 'Name the sites with -SiteUrl, or use -AllSites.' }$GraphAppId = '00000003-0000-0000-c000-000000000000'   # Microsoft Graph, same in every tenant$GraphV1 = 'https://graph.microsoft.com/v1.0'$RoleName = if ($AllSites) { 'Sites.ReadWrite.All' } else { 'Sites.Selected' }function Write-Step { param([string] $Text) Write-Host "`n== $Text" -ForegroundColor Cyan }function Write-Ok { param([string] $Text) Write-Host "   [ok]   $Text" -ForegroundColor Green }function Write-Skip { param([string] $Text) Write-Host "   [have] $Text" -ForegroundColor DarkGray }function Write-Note { param([string] $Text) Write-Host "   $Text" -ForegroundColor Gray }# Only Cloud Shell has no browser to sign in with; there a device code is the way in.# Elsewhere the browser is used, because many tenants block sign-in by code.$isCloudShell = [bool]$env:ACC_CLOUD -or ("$env:AZUREPS_HOST_ENVIRONMENT" -like '*cloud-shell*')$useDeviceCode = $isCloudShell# Runs az and returns its JSON output; a failed command stops the script.function Invoke-Az {    $output = & az @args --only-show-errors --output json    if ($LASTEXITCODE -ne 0) { throw "'az $($args[0]) $($args[1])' failed (exit code $LASTEXITCODE), see above." }    $text = ($output | Out-String).Trim()    if (-not $text) { return }    $parsed = $text | ConvertFrom-Json    return $parsed   # return, not the pipeline, so a JSON array arrives as its items}# One Microsoft Graph call through 'az rest'. The body goes through a file because# Windows PowerShell 5.1 and az.cmd both mangle quotes in JSON arguments.function Invoke-GraphAz {    param([string] $Method, [string] $Path, $Body)    $azArgs = @('rest', '--method', $Method, '--url', "$GraphV1/$Path")    $bodyFile = $null    if ($null -ne $Body) {        $bodyFile = [IO.Path]::GetTempFileName()        [IO.File]::WriteAllText($bodyFile, ($Body | ConvertTo-Json -Depth 8))        $azArgs += @('--body', "@$bodyFile", '--headers', 'Content-Type=application/json')    }    try { return Invoke-Az @azArgs }    finally { if ($bodyFile) { Remove-Item -LiteralPath $bodyFile -ErrorAction SilentlyContinue } }}function Get-AzCliAccount {    $ErrorActionPreference = 'Continue'   # 'not signed in' arrives on stderr    $text = (& az account show --output json 2>$null | Out-String).Trim()    if ($LASTEXITCODE -eq 0 -and $text) { return $text | ConvertFrom-Json }}# The application ids a site permission is granted to, from either property Graph returns.function Get-PermissionAppIds {    param($Permission)    foreach ($property in @('grantedToIdentitiesV2', 'grantedToIdentities')) {        if ($Permission.PSObject.Properties[$property]) {            foreach ($identity in @($Permission.$property)) {                if ($identity -and $identity.PSObject.Properties['application'] -and $identity.application) { $identity.application.id }            }        }    }}# A delegated Microsoft Graph token for Sites.FullControl.All, which Azure CLI cannot get.# It signs in through Microsoft's public client "Microsoft Graph Command Line Tools" (the# one Connect-MgGraph uses) without that module, whose current versions fail on older# PowerShell hosts. With a browser: authorization code with PKCE on a localhost redirect.# Without one (Cloud Shell): a device code, which some tenants block by Conditional Access.# The token stays in memory.$GraphCliClientId = '14d82eec-204b-4c2f-b7e8-296a70dab67e'function ConvertTo-Base64Url { param([byte[]] $Bytes) [Convert]::ToBase64String($Bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_') }function Get-BrowserToken {    param([string] $Tenant, [string] $Scope)    $probe = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0)    $probe.Start(); $port = $probe.LocalEndpoint.Port; $probe.Stop()    $redirect = "http://localhost:$port/"    $listener = [System.Net.HttpListener]::new()    $listener.Prefixes.Add($redirect)    $listener.Start()    try {        $random = [byte[]]::new(32)        [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($random)        $verifier = ConvertTo-Base64Url $random        $sha = [System.Security.Cryptography.SHA256]::Create()        $challenge = ConvertTo-Base64Url ($sha.ComputeHash([Text.Encoding]::ASCII.GetBytes($verifier)))        $state = [guid]::NewGuid().ToString('N')        $query = @{            client_id = $GraphCliClientId; response_type = 'code'; redirect_uri = $redirect; scope = $Scope            code_challenge = $challenge; code_challenge_method = 'S256'; state = $state; prompt = 'select_account'        }.GetEnumerator() | ForEach-Object { "$($_.Key)=$([Uri]::EscapeDataString($_.Value))" }        $url = "https://login.microsoftonline.com/$Tenant/oauth2/v2.0/authorize?" + ($query -join '&')        Write-Note 'A browser window opens for the sign-in. If it does not, open this address:'        Write-Note "  $url"        if ($IsMacOS) { & open $url } elseif ($IsLinux) { & xdg-open $url 2>$null } else { Start-Process $url }        $pending = $listener.GetContextAsync()        if (-not $pending.Wait([TimeSpan]::FromMinutes(5))) { throw 'No sign-in within 5 minutes. Run the script again.' }        $context = $pending.Result        $answer = $context.Request.QueryString        $page = [Text.Encoding]::UTF8.GetBytes('<html><body style="font-family:sans-serif">Signed in. You can close this tab and go back to PowerShell.</body></html>')        $context.Response.ContentType = 'text/html; charset=utf-8'        $context.Response.OutputStream.Write($page, 0, $page.Length)        $context.Response.Close()        if ($answer['error']) { throw "Sign-in failed: $($answer['error_description'])" }        if ($answer['state'] -ne $state) { throw 'Sign-in answer did not match this request.' }        $token = Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/$Tenant/oauth2/v2.0/token" -Body @{            grant_type = 'authorization_code'; client_id = $GraphCliClientId; code = $answer['code']            redirect_uri = $redirect; code_verifier = $verifier; scope = $Scope        }        return $token.access_token    }    finally { $listener.Stop(); $listener.Close() }}function Get-DeviceCodeToken {    param([string] $Tenant, [string] $Scope)    $base = "https://login.microsoftonline.com/$Tenant/oauth2/v2.0"    $code = Invoke-RestMethod -Method POST -Uri "$base/devicecode" -Body @{ client_id = $GraphCliClientId; scope = $Scope }    Write-Host "   $($code.message)" -ForegroundColor Yellow    $deadline = (Get-Date).AddSeconds([int]$code.expires_in)    $interval = [int]$code.interval    while ((Get-Date) -lt $deadline) {        Start-Sleep -Seconds $interval        try {            $token = Invoke-RestMethod -Method POST -Uri "$base/token" -Body @{                grant_type = 'urn:ietf:params:oauth:grant-type:device_code'; client_id = $GraphCliClientId; device_code = $code.device_code            }            return $token.access_token        }        catch {            $reason = try { ($_.ErrorDetails.Message | ConvertFrom-Json).error } catch { '' }            if ($reason -eq 'authorization_pending') { continue }            if ($reason -eq 'slow_down') { $interval += 5; continue }            if ($reason -in @('access_denied', 'invalid_grant')) {                throw ('Sign-in with a code was refused; your organisation may block it. Run this script on your own ' +                       'computer instead (PowerShell with Azure CLI), where the sign-in opens a browser.')            }            throw        }    }    throw 'The sign-in code expired. Run the script again.'}if ($WhatIfPreference) { Write-Host 'DRY RUN - nothing will be changed.' -ForegroundColor Yellow }# -- 1. sign-in -----------------------------------------------------------------------Write-Step '1/3 Sign-in'if (-not (Get-Command az -ErrorAction SilentlyContinue)) {    throw 'Azure CLI (az) was not found. Run this script in Azure Cloud Shell (PowerShell).'}$account = Get-AzCliAccountif (-not $account -or ($TenantId -and $account.tenantId -ne $TenantId)) {    $login = @('login', '--allow-no-subscriptions', '--only-show-errors', '--output', 'none')    if ($TenantId) { $login += @('--tenant', $TenantId) }    if ($useDeviceCode) { $login += '--use-device-code' }    & az @login    if ($LASTEXITCODE -ne 0) { throw 'az login failed.' }    $account = Get-AzCliAccount}$tenantId = $account.tenantId$tenantName = (@((Invoke-GraphAz GET 'organization?$select=displayName').value) | Select-Object -First 1).displayNameWrite-Note "tenant:  $tenantName ($tenantId)"Write-Note "account: $($account.user.name)"$app = Invoke-Az ad app show --id $AppId$AppName = $app.displayName$appId = $app.appId$sp = Invoke-Az ad sp list --spn $appId | Select-Object -First 1if (-not $sp) { throw "The app $appId has no service principal. Run New-HiveBDCSharePointApp.ps1 first." }Write-Note "app:     $AppName ($appId)"Write-Note "access:  $(if ($AllSites) { 'Sites.ReadWrite.All, every site' } else { 'Sites.Selected, write on the sites below' })"foreach ($url in $SiteUrl) { Write-Note "site:    $url" }if (-not $Force -and -not $WhatIfPreference) {    $answer = Read-Host "   Grant this access in '$tenantName'? (y/n)"    if ($answer -notmatch '^(y|yes|j|ja)$') { Write-Note 'Stopped. Nothing was changed.'; return }}# -- 2. permission and admin consent ---------------------------------------------------Write-Step "2/3 Permission $RoleName"$graphSp = Invoke-Az ad sp show --id $GraphAppId$role = @($graphSp.appRoles | Where-Object { $_.value -eq $RoleName -and $_.allowedMemberTypes -contains 'Application' }) |    Select-Object -First 1# Listing the permission makes it show under "API permissions"; the consent below grants it.$listed = @($app.requiredResourceAccess | Where-Object { $_.resourceAppId -eq $GraphAppId } |    ForEach-Object { $_.resourceAccess } | Where-Object { $_.id -eq $role.id })if ($listed) { Write-Skip "$RoleName is listed" }elseif ($PSCmdlet.ShouldProcess($AppName, "List the permission $RoleName")) {    Invoke-Az ad app permission add --id $appId --api $GraphAppId --api-permissions "$($role.id)=Role" | Out-Null    Write-Ok "listed $RoleName"}$consented = @((Invoke-GraphAz GET "servicePrincipals/$($sp.id)/appRoleAssignments").value |    Where-Object { $_.appRoleId -eq $role.id -and $_.resourceId -eq $graphSp.id })if ($consented) { Write-Skip "$RoleName is consented" }elseif ($PSCmdlet.ShouldProcess($AppName, "Grant admin consent for $RoleName")) {    Invoke-GraphAz POST "servicePrincipals/$($sp.id)/appRoleAssignments" @{        principalId = $sp.id; resourceId = $graphSp.id; appRoleId = $role.id    } | Out-Null    Write-Ok "$RoleName consented"}# -- 3. write access per site ---------------------------------------------------------$failed = @()if ($AllSites) { Write-Step '3/3 Sites (not needed with -AllSites)' }else {    Write-Step '3/3 Write access on the sites'    Write-Note 'Granting a site needs Sites.FullControl.All for your account; sign in once more:'    $scope = 'https://graph.microsoft.com/Sites.FullControl.All'    $graphToken = if ($useDeviceCode) { Get-DeviceCodeToken $tenantId $scope } else { Get-BrowserToken $tenantId $scope }    $headers = @{ Authorization = "Bearer $graphToken" }    foreach ($url in $SiteUrl) {        $uri = [Uri]$url        $segments = @($uri.AbsolutePath.Trim('/').Split('/') | Where-Object { $_ })        $siteRef = if ($segments.Count -ge 2 -and $segments[0] -in @('sites', 'teams')) {            "$($uri.Host):/$($segments[0])/$([Uri]::UnescapeDataString($segments[1]))"        } else { $uri.Host }        try {            $site = Invoke-RestMethod -Headers $headers -Uri "$GraphV1/sites/$siteRef`?`$select=id,webUrl"            $permissions = Invoke-RestMethod -Headers $headers -Uri "$GraphV1/sites/$($site.id)/permissions"            $existing = @($permissions.value | Where-Object { (Get-PermissionAppIds $_) -contains $appId }) | Select-Object -First 1            if ($existing -and @($existing.roles | Where-Object { $_ -in @('write', 'owner', 'fullcontrol') })) {                Write-Skip "$($site.webUrl): $($existing.roles -join ', ')"            }            elseif ($existing) {                if ($PSCmdlet.ShouldProcess($site.webUrl, 'Raise the access to write')) {                    Invoke-RestMethod -Headers $headers -Method PATCH -Uri "$GraphV1/sites/$($site.id)/permissions/$($existing.id)" `                        -Body (@{ roles = @('write') } | ConvertTo-Json) -ContentType 'application/json' | Out-Null                    Write-Ok "$($site.webUrl): raised to write"                }            }            elseif ($PSCmdlet.ShouldProcess($site.webUrl, 'Grant write access')) {                $body = @{ roles = @('write'); grantedToIdentities = @(@{ application = @{ id = $appId; displayName = $AppName } }) }                Invoke-RestMethod -Headers $headers -Method POST -Uri "$GraphV1/sites/$($site.id)/permissions" `                    -Body ($body | ConvertTo-Json -Depth 5) -ContentType 'application/json' | Out-Null                Write-Ok "$($site.webUrl): write"            }        }        catch {            $failed += $url            $detail = if ($_.ErrorDetails.Message) { $_.ErrorDetails.Message } else { $_.Exception.Message }            Write-Warning "$url : $detail"            Write-Note 'Your account needs SharePoint Administrator and has to be a member of this site.'        }    }}# -- next -----------------------------------------------------------------------------Write-Host "`nDONE" -ForegroundColor YellowWrite-Host "  Tenant ID  $tenantId"Write-Host "  Client ID  $appId"if ($failed) { Write-Host "  NOT granted: $($failed -join ', ') (fix the cause above and run again)" -ForegroundColor Red }Write-Note 'Hive BDC dashboard: Settings > Connections > SharePoint, then Test SharePoint.'

Hive BDC läuft mit einer Lizenz von Balsoft. Ohne Lizenz öffnet sich das Dashboard, es werden aber keine Belege verarbeitet. Sprechen Sie uns an für eine Lizenz oder eine Testinstallation.

Kontakt aufnehmen