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
- Setup herunterladen (130 MB, von Balsoft signiert)
- Dienst und Dashboard installieren
- Dynamics-Modul durch Balsoft eingespielt
- Testbeleg als XRechnung senden
- Go-live
D365 F&O · AX 2012 · AX 2009
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
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.
Die Rechnung wird in Dynamics gebucht
Eingangsrechnungen (AP): So kommt eine E-Rechnung in Dynamics
Von der E-Rechnung Ihres Lieferanten im Postfach, über Peppol, im Ordner oder in Ihrem DMS (zum Beispiel SharePoint) bis zur Kreditorenrechnung in AX 2009, AX 2012 oder D365 F&O, ohne Abtippen.
Die E-Rechnung des Lieferanten kommt an
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.2Fü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.2Fü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
Dynamics AX 2012
E-Rechnung für Microsoft Dynamics AX 2012
E-Rechnung aus Microsoft Dynamics AX 2012 R3 ohne Upgrade: XRechnung 3.0.2 und ZUGFeRD 2.5.2, geprüft nach EN 16931, per Mail an Ihre Kunden. Mit Handbuch.
Mehr erfahrenDynamics AX 2009
E-Rechnung für Microsoft Dynamics AX 2009
E-Rechnung aus Microsoft Dynamics AX 2009: XRechnung 3.0.2 und ZUGFeRD 2.5.2, geprüft nach EN 16931, auch mit den PDFs, die AX 2009 druckt. Ohne Upgrade.
Mehr erfahrenDynamics 365 F&O
E-Rechnung für D365 F&O: Dynamics 365 Finance & Operations
E-Rechnung aus D365FO und Dynamics 365 F&O: XRechnung 3.0.2 und ZUGFeRD 2.5.2 mit Hive BDC, geprüft nach EN 16931, per Mail versendet, im DMS abgelegt.
Mehr erfahrenPasst zu Ihrem DMS: SharePoint und ShareFlex direkt; DocuWare, d.velop documents, ELO, M-Files, enaio, windream, SER Doxis, nscale, EASY archive, Laserfiche, OpenText und andere Dokumentenmanagementsysteme über den Ausgabeordner, den sie mit ihrem Ordnerimport oder ihrem eigenen Connector lesen.
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
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 ansehenSystemvoraussetzungen
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.
Server
- Windows Server 2016, 2019, 2022 oder 2025, 64 Bit, mit Desktopdarstellung. Für Testsysteme Windows 10 oder 11, 64 Bit.
- Sonst nichts zu installieren: Das Setup bringt die nötige .NET-Laufzeit mit.
- Etwa 250 MB für das Programm, dazu Platz für Belege und Protokolle (30 Tage aufbewahrt).
- Lokale Administratorrechte für die Installation. Der Dienst läuft als LocalSystem, oder als Domänenkonto, wenn der Exportordner auf einer Netzwerkfreigabe liegt.
Dynamics
- Dynamics AX 2012 R3 oder Dynamics AX 2009, auch Dynamics 365 F&O on-premises.
- Das Hive-BDC-Modul im ERP, geliefert und installiert von Balsoft.
- Ein Batchserver, der die Hive-BDC-Exportaufträge ausführt.
Exportordner
- Ein lokaler Ordner oder eine Netzwerkfreigabe, in die das ERP die Belege schreibt und aus der Hive BDC sie abholt.
- Lese- und Schreibzugriff für das Dienstkonto des ERP und das Dienstkonto von Hive BDC.
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 herunterladenSHA-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.
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 Mail“ ohne Berechtigungen an und gibt die Client-ID aus. Braucht die Rolle Anwendungsadministrator.
Invoke-WebRequest https://balsoft.de/downloads/hive-bdc/New-HiveBDCMailApp.ps1 -OutFile New-HiveBDCMailApp.ps1./New-HiveBDCMailApp.ps1<#.SYNOPSIS Step 1 of 2 for Mail: creates the app registration "Hive BDC Mail", 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-HiveBDCMailAccess.ps1, which assigns the right to send as one mailbox. Role: Application Developer or Application Administrator. No client secret is created; the script prints how. -WhatIf shows the plan only..EXAMPLE ./New-HiveBDCMailApp.ps1#>#Requires -Version 5.1[CmdletBinding(SupportsShouldProcess = $true)]param( [ValidateLength(3, 120)] [string] $AppName = 'Hive BDC Mail', [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-HiveBDCMailAccess.ps1 -AppId $appId -SenderMailbox <mailbox@domain>"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
Erlaubt der App in Exchange Online, nur als das eine genannte Postfach zu senden, ohne mandantenweite Mail.Send-Zustimmung in Entra ID. Verwenden Sie die Client-ID aus Schritt 1. Braucht Exchange-Administrator.
Invoke-WebRequest https://balsoft.de/downloads/hive-bdc/Grant-HiveBDCMailAccess.ps1 -OutFile Grant-HiveBDCMailAccess.ps1./Grant-HiveBDCMailAccess.ps1 -AppId <client-id> -SenderMailbox invoices@contoso.com<#.SYNOPSIS Step 2 of 2 for mail: allows the Hive BDC Mail app to send as ONE mailbox, and as no other..DESCRIPTION Run in Azure Cloud Shell (PowerShell) after New-HiveBDCMailApp.ps1. Steps, each skipped when already in place: 1. Azure CLI: show the tenant, the app and the mailbox, and ask before changing anything. 2. Exchange Online: RBAC for Applications, the role "Application Mail.Send" limited to a management scope that contains only -SenderMailbox. The app gets NO Mail.Send consent in Entra ID, because an Entra consent is tenant-wide and RBAC grants add to it instead of narrowing it; an existing Entra consent is removed. Tenants without RBAC for Applications get the older application access policy, which does restrict an Entra consent. Role: Exchange Administrator (plus Privileged Role Administrator only to remove an old Entra consent, or for the access policy fallback). -WhatIf shows the plan only..EXAMPLE ./Grant-HiveBDCMailAccess.ps1 -AppId 11111111-2222-3333-4444-555555555555 -SenderMailbox invoices@contoso.com#>#Requires -Version 5.1[CmdletBinding(SupportsShouldProcess = $true)]param( # Application (client) ID printed by New-HiveBDCMailApp.ps1. [Parameter(Mandatory = $true)] [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')] [string] $AppId, [Parameter(Mandatory = $true)] [ValidatePattern('^[^@\s]+@[^@\s]+\.[^@\s]+$')] [string] $SenderMailbox, # Prefix of the Exchange objects (scope, role assignment, security group). [ValidatePattern('^[A-Za-z0-9-]{3,40}$')] [string] $Name = 'HiveBDCMail', [switch] $UseApplicationAccessPolicy, [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'$GraphAppId = '00000003-0000-0000-c000-000000000000' # Microsoft Graph, same in every tenant$GraphV1 = 'https://graph.microsoft.com/v1.0'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 }}function Test-Cmdlet { param([string] $CmdletName) [bool](Get-Command $CmdletName -ErrorAction SilentlyContinue) }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-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-HiveBDCMailApp.ps1 first." }Write-Note "app: $AppName ($appId)"Write-Note "mailbox: $SenderMailbox"if (-not $Force -and -not $WhatIfPreference) { $answer = Read-Host " Allow it to send as $SenderMailbox only? (y/n)" if ($answer -notmatch '^(y|yes|j|ja)$') { Write-Note 'Stopped. Nothing was changed.'; return }}# The tenant-wide Entra consent, if someone granted one; step 2 decides what happens to it.$graphSp = Invoke-Az ad sp show --id $GraphAppId$mailSend = @($graphSp.appRoles | Where-Object { $_.value -eq 'Mail.Send' -and $_.allowedMemberTypes -contains 'Application' }) | Select-Object -First 1$entraGrant = @((Invoke-GraphAz GET "servicePrincipals/$($sp.id)/appRoleAssignments").value | Where-Object { $_.appRoleId -eq $mailSend.id -and $_.resourceId -eq $graphSp.id }) | Select-Object -First 1# -- 3. Exchange Online ---------------------------------------------------------------Write-Step '2/2 Exchange Online: send as one mailbox only'if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) { Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser -Force -AllowClobber}Import-Module ExchangeOnlineManagementif ($useDeviceCode) { Connect-ExchangeOnline -Device -ShowBanner:$false } else { Connect-ExchangeOnline -ShowBanner:$false }if (Test-Cmdlet 'Get-ConnectionInformation') { $exoTenant = @(Get-ConnectionInformation)[0].TenantID if ($exoTenant -and "$exoTenant" -ne $tenantId) { Disconnect-ExchangeOnline -Confirm:$false | Out-Null throw "Exchange Online signed in to tenant $exoTenant, but the app is in $tenantId." }}$mailbox = Get-Mailbox -Identity $SenderMailbox -ErrorAction SilentlyContinueif (-not $mailbox) { throw "The mailbox '$SenderMailbox' was not found in Exchange Online." }$useRbac = (Test-Cmdlet 'New-ServicePrincipal') -and (Test-Cmdlet 'New-ManagementRoleAssignment') -and -not $UseApplicationAccessPolicyif ($useRbac) { $scopeName = "$Name-Scope" $assignmentName = "$Name-MailSend" if (Get-ServicePrincipal -Identity $appId -ErrorAction SilentlyContinue) { Write-Skip 'registered in Exchange Online' } elseif ($PSCmdlet.ShouldProcess($appId, 'Register the service principal in Exchange Online')) { # Exchange needs the service principal's OBJECT id, not the application id. New-ServicePrincipal -AppId $appId -ObjectId $sp.id -DisplayName $AppName | Out-Null Write-Ok 'registered in Exchange Online' } # Custom scopes need the one-time switch Enable-OrganizationCustomization, which tenants # that never customised Exchange have off ("isn't currently allowed in your organization"). if (-not (Get-OrganizationConfig).IsDehydrated) { Write-Skip 'organisation customization is enabled' } elseif ($PSCmdlet.ShouldProcess('Exchange Online organisation', 'Enable-OrganizationCustomization (one-time, permanent)')) { Enable-OrganizationCustomization Write-Ok 'enabled organisation customization (needed once for custom scopes)' } $scope = Get-ManagementScope -Identity $scopeName -ErrorAction SilentlyContinue if ($scope) { Write-Skip "scope '$scopeName': $($scope.RecipientFilter)" if ($scope.RecipientFilter -notmatch [regex]::Escape($SenderMailbox)) { Write-Warning "The scope '$scopeName' does NOT match $SenderMailbox. Review it, or use another -Name." } } elseif ($PSCmdlet.ShouldProcess($scopeName, "Create a management scope with only $SenderMailbox")) { # Doubled apostrophes keep an address with ' from breaking the filter. $filter = "PrimarySmtpAddress -eq '{0}'" -f $SenderMailbox.Replace("'", "''") try { New-ManagementScope -Name $scopeName -RecipientRestrictionFilter $filter -ErrorAction Stop | Out-Null } catch { if ($_.Exception.Message -notmatch 'OrganizationCustomization') { throw } # Exchange applies the switch with a delay of up to about an hour. Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue | Out-Null Write-Host '' Write-Host ' Exchange Online has not applied the customization switch yet; that takes up to an hour.' -ForegroundColor Yellow Write-Host ' Run this script again later with the same parameters. Everything done so far is skipped,' -ForegroundColor Yellow Write-Host ' and the app cannot send mail until it has finished.' -ForegroundColor Yellow return } Write-Ok "created the scope '$scopeName'" } if (Get-ManagementRoleAssignment -Identity $assignmentName -ErrorAction SilentlyContinue) { Write-Skip "role assignment '$assignmentName'" } elseif ($PSCmdlet.ShouldProcess($assignmentName, "Assign 'Application Mail.Send' limited to $scopeName")) { New-ManagementRoleAssignment -Name $assignmentName -App $appId -Role 'Application Mail.Send' ` -CustomResourceScope $scopeName | Out-Null Write-Ok "assigned 'Application Mail.Send' for $SenderMailbox" } # An Entra consent would add tenant-wide send-as on top of the scoped role. if (-not $entraGrant) { Write-Skip 'no tenant-wide Mail.Send consent in Entra ID (correct)' } elseif ($PSCmdlet.ShouldProcess($AppName, 'Remove the tenant-wide Mail.Send consent from Entra ID')) { Invoke-GraphAz DELETE "servicePrincipals/$($sp.id)/appRoleAssignments/$($entraGrant.id)" | Out-Null Write-Ok 'removed the tenant-wide Mail.Send consent from Entra ID' } $verify = "Test-ServicePrincipalAuthorization -Identity $appId -Resource $SenderMailbox"}else { # Older tenants: Entra consent for Mail.Send, restricted by an application access # policy to a mail-enabled SECURITY group (a Microsoft 365 group does not work). if (-not (Test-Cmdlet 'New-ApplicationAccessPolicy')) { throw 'Neither RBAC for Applications nor application access policies are available. Update ExchangeOnlineManagement and retry.' } $groupAlias = $Name.ToLowerInvariant() $groupAddress = "$groupAlias@$($SenderMailbox.Split('@')[1])" if (Get-DistributionGroup -Identity $groupAddress -ErrorAction SilentlyContinue) { Write-Skip "group $groupAddress" } elseif ($PSCmdlet.ShouldProcess($groupAddress, 'Create the mail-enabled security group')) { New-DistributionGroup -Name $Name -Alias $groupAlias -PrimarySmtpAddress $groupAddress -Type Security | Out-Null Write-Ok "created the group $groupAddress" } $members = @(Get-DistributionGroupMember -Identity $groupAddress -ErrorAction SilentlyContinue | ForEach-Object { $_.PrimarySmtpAddress }) if ($members -contains $mailbox.PrimarySmtpAddress) { Write-Skip "$SenderMailbox is a member" } elseif ($PSCmdlet.ShouldProcess($groupAddress, "Add $SenderMailbox")) { Add-DistributionGroupMember -Identity $groupAddress -Member $SenderMailbox Write-Ok "added $SenderMailbox to the group" } if (@(Get-ApplicationAccessPolicy -ErrorAction SilentlyContinue | Where-Object { $_.AppId -eq $appId })) { Write-Skip 'application access policy' } elseif ($PSCmdlet.ShouldProcess($appId, "Restrict the app to $groupAddress")) { New-ApplicationAccessPolicy -AppId $appId -PolicyScopeGroupId $groupAddress -AccessRight RestrictAccess ` -Description "Hive BDC may send only as members of $groupAddress" | Out-Null Write-Ok 'created the application access policy' } # The consent comes last, so it is never in place without the policy that limits it. if ($entraGrant) { Write-Skip 'Mail.Send consented in Entra ID' } elseif ($PSCmdlet.ShouldProcess($AppName, 'Grant admin consent for Mail.Send')) { Invoke-GraphAz POST "servicePrincipals/$($sp.id)/appRoleAssignments" @{ principalId = $sp.id; resourceId = $graphSp.id; appRoleId = $mailSend.id } | Out-Null Write-Ok 'Mail.Send consented, limited by the policy above' } $verify = "Test-ApplicationAccessPolicy -Identity $SenderMailbox -AppId $appId"}Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue | Out-Null# -- next -----------------------------------------------------------------------------Write-Host "`nDONE" -ForegroundColor YellowWrite-Host " Tenant ID $tenantId"Write-Host " Client ID $appId"Write-Host " Send from $SenderMailbox"Write-Note 'Hive BDC dashboard: Settings > Connections > Document mail, then Test mail.'Write-Note 'Exchange needs up to 30 minutes to apply this; until then sending can fail with ErrorAccessDenied.'Write-Note "Check later: $verify"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