Cloudflare: Add DNS Records with PowerShell

Modified on Thu, 14 May at 4:56 PM

# permissions
# Zone.Single Redirect, Zone.DNS

$bearerheader = @{ "Authorization" = "Bearer xxxxx" }

# 1. Specify your list of new domains
$targetDomains = @(
    "domain1.net",
    "domain2.com",
    "domain3.us"
)

# 2. Define the new records
$mxRecord = @{
    type     = "MX"
    name     = "@"
    content  = "mx.domain.com"
    priority = 0
} | ConvertTo-Json

$spfRecord = @{
    type    = "TXT"
    name    = "@"
    content = "v=spf1 include:_spf.google.com -all"
} | ConvertTo-Json

foreach ($domainName in $targetDomains) {
    Write-Host "---------------------------------"
    Write-Host "Processing $domainName..." -ForegroundColor Cyan
    
    try {
        # Get the Zone ID for the domain name
        $zoneResponse = Invoke-WebRequest -Uri "https://api.cloudflare.com/client/v4/zones?name=$domainName" `
            -Method Get `
            -Headers $bearerheader `
            -ContentType "application/json" `
            -UseBasicParsing
            
        $zoneData = ($zoneResponse.Content | ConvertFrom-Json).result
        
        if ($null -eq $zoneData -or $zoneData.Count -eq 0) {
            Write-Warning "  [!] Could not find zone '$domainName' in the Cloudflare account. Skipping."
            continue
        }
        
        $zoneId = $zoneData[0].id
        Write-Host "  [*] Zone ID is $zoneId"

        # Add MX Record
        Write-Host "  [+] Adding MX record..." -ForegroundColor Green
        try {
            Invoke-WebRequest -Uri "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records" `
                -Method Post `
                -Headers $bearerheader `
                -ContentType "application/json" `
                -Body $mxRecord `
                -UseBasicParsing | Out-Null
        } catch {
            Write-Host "      [X] MX Record Failed!" -ForegroundColor Red
            # Extract and display the hidden Cloudflare error message
            if ($_.Exception.Response) {
                $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
                $responseBody = $reader.ReadToEnd()
                $cfError = $responseBody | ConvertFrom-Json
                foreach ($err in $cfError.errors) {
                    Write-Host "      -> Cloudflare Error [$($err.code)]: $($err.message)" -ForegroundColor Red
                }
            } else {
                Write-Host "      -> $($_.Exception.Message)" -ForegroundColor Red
            }
        }

        # Add SPF Record
        Write-Host "  [+] Adding SPF record..." -ForegroundColor Green
        try {
            Invoke-WebRequest -Uri "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records" `
                -Method Post `
                -Headers $bearerheader `
                -ContentType "application/json" `
                -Body $spfRecord `
                -UseBasicParsing | Out-Null
        } catch {
            Write-Host "      [X] SPF Record Failed!" -ForegroundColor Red
            # Extract and display the hidden Cloudflare error message
            if ($_.Exception.Response) {
                $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
                $responseBody = $reader.ReadToEnd()
                $cfError = $responseBody | ConvertFrom-Json
                foreach ($err in $cfError.errors) {
                    Write-Host "      -> Cloudflare Error [$($err.code)]: $($err.message)" -ForegroundColor Red
                }
            } else {
                Write-Host "      -> $($_.Exception.Message)" -ForegroundColor Red
            }
        }

    } catch {
        Write-Warning "  [!] A critical error occurred while processing $domainName : $($_.Exception.Message)"
    }
}

Write-Host "---------------------------------"
Write-Host "Done!" -ForegroundColor Cyan

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article