Public/TenantConfiguration/Enable-CustomerDKIM.ps1

function Get-MainDomain {
    param (
        [string]$domain
    )

    # Split the domain into its components
    $domainParts = $domain -split '\.'

    # If the domain has more than two parts, return the last two parts
    if ($domainParts.Length -gt 2) {
        return ($domainParts[-2..-1] -join '.')
    } else {
        return $domain
    }
}

# Function to get the subdomain part of the domain
function Get-Subdomain {
    param (
        [string]$domain
    )

    # Split the domain into its components
    $domainParts = $domain -split '\.'

    # If the domain has more than two parts, return all but the last two parts
    if ($domainParts.Length -gt 2) {
        return ($domainParts[0..($domainParts.Length - 3)] -join '.')
    } else {
        return ""
    }
}

function Is-Subdomain {
    param (
        [string]$domain
    )

    # Split the domain into its components
    $domainParts = $domain -split '\.'

    # If the domain has more than two parts, return all but the last two parts
    if ($domainParts.Length -gt 2) {
        return $true
    } else {
        return $false
    }
}

function Enable-CustomerDKIM() {
    param(
        [Parameter(Mandatory)]
        [string]$TenantId
    )

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

    try {
        Write-Host "[DKIM] Connecting to Customer environment.." -ForegroundColor Yellow
        Connect-CustomerExchange -CustomerTenantId $TenantId
        Connect-CustomerGraph -CustomerTenantId $TenantId

        $DomainsWithoutDKIM = @()

        Get-MgDomain | Where-Object { $_.Id -NotLike '*.onmicrosoft.com' } | ForEach-Object {
            Write-Host "[$($_.Id)] Checking domain.." -ForegroundColor Yellow

            $DKIMStatus = Get-DkimSigningConfig -Identity $_.Id -ErrorAction SilentlyContinue

            if( -not $DKIMStatus  -or $DKIMStatus.Enabled -eq $false) {
                $DomainsWithoutDKIM += [pscustomobject]@{
                    Domain = $_.Id
                }
            }
        }
    
        if ( $DomainsWithoutDKIM.Count -eq 0 ) {
            Write-Host "[DKIM] No domains without DKIM found." -ForegroundColor Green
            return
        }
    
        $SelectedDomains = $DomainsWithoutDKIM | Out-ConsoleGridView -Title "Select domains to enable DKIM for.." -OutputMode Multiple
    
        $SelectedDomains | ForEach-Object {
            $Domain = $_
            $DomainName = $Domain.Domain
        
            Write-Host "[$($DomainName)] Getting DKIM configuration..." -ForegroundColor Yellow
        
            $DKIMConfig = Get-DkimSigningConfig -Identity $DomainName -ErrorAction SilentlyContinue
        
            if ( -not $DKIMConfig ) {
                Write-Host "[$($DomainName)] DKIM signing config not found. Trying to enable." -ForegroundColor Yellow
                New-DkimSigningConfig -DomainName $DomainName -Enabled $false -ErrorAction SilentlyContinue | Out-Null
                $DKIMConfig = Get-DkimSigningConfig -Identity $DomainName -ErrorAction SilentlyContinue
            }
        
            if ( $DKIMConfig ) {
                if ( $DKIMConfig.Enabled ) {
                    Write-Host "[$($DomainName)] DKIM signing config is enabled. Skipping..." -ForegroundColor Yellow
                }
                else {
                    $cname1 = "selector1._domainkey.$($DomainName)"
                    $cname2 = "selector2._domainkey.$($DomainName)"
                
                    $CreateManual = $false

                    # Used if the domain is a subdomain
                    $MainDomain = Get-MainDomain -Domain $DomainName
                    
                    $cname1Dns = Resolve-DnsName -Name $cname1 -Type CNAME -ErrorAction SilentlyContinue
                    $cname2Dns = Resolve-DnsName -Name $cname2 -Type CNAME -ErrorAction SilentlyContinue
                    $NameServer = Resolve-DnsName -Name $MainDomain -Type NS -ErrorAction SilentlyContinue
                
                    Write-Host "[$($DomainName)] Checking DNS records..." -ForegroundColor Yellow
                
                    if ( !$cname1Dns.NameHost -and !$cname2Dns.NameHost ) {
                        Write-Host "[$($DomainName)] CNAME records not found." -ForegroundColor Yellow
                        Write-Host "[$($DomainName)] Checking nameservers..." -ForegroundColor Yellow
                    
                        if( $NameServer.NameHost -notlike '*.curanet.dk' ) {
                            Write-Host "[$($DomainName)] Nameservers are not curanet.dk." -ForegroundColor Yellow
                            $CreateManual = $true
                        }
                        else {
                            $DNSRecords = Get-CuraDNSRecords -DomainName $MainDomain
                        
                            if ( $DNSRecords.status -ne 404 ) {
                                Write-Host "[$($DomainName)] Domain found on curanet." -ForegroundColor Yellow
                                Write-Host "[$($DomainName)] Trying to create first cname record... " -ForegroundColor Yellow -NoNewline

                                if(Is-Subdomain -domain $DomainName) {
                                    $Subdomain = Get-Subdomain -domain $DomainName
                                    $Selector1 = "selector1._domainkey.$($Subdomain)"
                                    $Selector2 = "selector2._domainkey.$($Subdomain)"
                                } else {
                                    $Selector1 = "selector1._domainkey"
                                    $Selector2 = "selector2._domainkey"
                                }
                            
                                $Cname1Result = New-CuraDNSRecord -DomainName $MainDomain -Hostname $Selector1 -Type 'CNAME' -Value $($DKIMConfig.Selector1CNAME.Trim())
                            
                                if ( -not $Cname1Result.status ) {
                                    Write-Host "SUCCESS!" -ForegroundColor Green
                                }
                            
                                else {
                                    Write-Host "FAILED!" -ForegroundColor Red
                                    $CreateManual = $true
                                }
                            
                                Write-Host "[$($DomainName)] Trying to create second cname record... " -ForegroundColor Yellow -NoNewline
                            
                                $Cname2Result = New-CuraDNSRecord -DomainName $MainDomain -Hostname $Selector2 -Type 'CNAME' -Value $($DKIMConfig.Selector2CNAME.Trim())
                            
                                if( -not $Cname2Result.status ) {
                                    Write-Host "SUCCESS!" -ForegroundColor Green
                                }
                            
                                else {
                                    Write-Host "FAILED!" -ForegroundColor Red
                                    $CreateManual = $true
                                }
                            }
                        
                            else {
                                Write-Host "[$($DomainName)] Domain not found on curanet." -ForegroundColor Yellow
                                $CreateManual = $true
                            }
                        }
                        if ( $CreateManual ) {
                            Write-Host "[$($DomainName)] Please create the following CNAME records manually:" -ForegroundColor Cyan
                            Write-Host "[$($DomainName)] selector1._domainkey.$($DomainName) -> $($DKIMConfig.Selector1CNAME.Trim())" -ForegroundColor Cyan
                            Write-Host "[$($DomainName)] selector2._domainkey.$($DomainName) -> $($DKIMConfig.Selector2CNAME.Trim())" -ForegroundColor Cyan
                            Write-Host "[$($DomainName)] Press any key to continue..." -ForegroundColor Cyan
                            Read-Host
                        }
                    }
                    else {
                        Write-Host "[$($DomainName)] CNAME records found." -ForegroundColor Yellow
                    }
                
                    Write-Host "[$($DomainName)] Enabling DKIM" -ForegroundColor Yellow -NoNewline

                    Set-DkimSigningConfig -Identity $DomainName -Enabled $true -ErrorAction SilentlyContinue | Out-Null

                    While(1) {
                        Write-Host "." -ForegroundColor Yellow -NoNewline
                        $result = Get-DkimSigningConfig -Identity $DomainName -ErrorAction SilentlyContinue
                    
                        if($result.Enabled -eq $true) {
                            Write-Host " Done!" -ForegroundColor Green
                            break
                        }
                    
                        Set-DkimSigningConfig -Identity $DomainName -Enabled $true -ErrorAction SilentlyContinue | Out-Null
                        Start-Sleep -Seconds 5
                   }
                }
            }
            else {
                Write-Host "[$($DomainName)] Could not enable DKIM Signing config. -Maybe exchange has not propagated yet on the tenant!" -ForegroundColor Red
            }
        }
    }
    catch {
        throw "Failed to enable DKIM: $_"
    }
}