Public/TenantConfiguration/Enable-CustomerDMARC.ps1

function Enable-CustomerDMARC {

    param(
        [Parameter(Mandatory)]
        [string]$TenantId,

        [Parameter()]
        [array]$Domains = @()
    )

    Write-Host "[DMARC] Starting DMARC configuration.." -ForegroundColor Yellow

    try {
        Connect-CustomerGraph -CustomerTenantId $TenantId
        
        if ( $Domains.Count -eq 0 ) {

            $TenantDomains = Get-MgDomain | Where-Object { $_.Id -NotLike '*.onmicrosoft.com' }

            $Domains = @()
    
            $TenantDomains | ForEach-Object {
                Write-Host "[$($_.Id)] Checking domain.." -ForegroundColor Yellow
    
                $DMARCRecord = Resolve-DnsName -Name "_dmarc.$($_.Id)" -Type TXT -ErrorAction SilentlyContinue
                if( $null -eq $DMARCRecord.Strings) {
                    $Domains += $_.Id
                }
            }

            if ( $Domains.Count -eq 0 ) {
                Write-Host "[DMARC] No domains without DMARC found." -ForegroundColor Green
                return
            }

            $Domains = $Domains | Out-ConsoleGridView -Title "Select domains to enable DMARC for" -OutputMode Multiple
        }
        if(!$Domains) {
            Write-Host "[DMARC] No domains selected. Exiting.." -ForegroundColor Yellow
            return
        }

        $Domains | ForEach-Object {
            $CreateManual = $false
            $DomainName = $_
            $NameServer = Resolve-DnsName -Name $DomainName -Type NS -ErrorAction SilentlyContinue

            if ( $NameServer -and $NameServer.NameHost -like '*.curanet.dk' ) {
                $DNSRecords = Get-CuraDNSRecords -Domain $DomainName

                if ( $DNSRecords.status -ne 404 ) {
                    $Result = New-CuraDNSRecord -DomainName $DomainName -Hostname '_dmarc' -Type 'TXT' -Value "v=DMARC1; p=reject;"

                    if ( !$Result.status ) {
                        Write-Host "[$($DomainName)] DMARC record created successfully." -ForegroundColor Green
                    }
                    else {
                        $CreateManual = $true
                    }
                }
            }

            else {
                $CreateManual = $true
            }

            if ( $CreateManual ) {
                Write-Host "[$($DomainName)] DMARC record could not be created automatically. Please create the following record manually:" -ForegroundColor Cyan
                Write-Host "[$($DomainName)] Hostname: _dmarc" -ForegroundColor Cyan
                Write-Host "[$($DomainName)] Type: TXT" -ForegroundColor Cyan
                Write-Host "[$($DomainName)] Value: v=DMARC1; p=reject;" -ForegroundColor Cyan
            }
        }

        Write-Host "[DMARC] DMARC configuration completed." -ForegroundColor Yellow
    }
    catch {
        throw "Failed to enable DMARC: $_"
    }
}