Get-SpfLookupCount.ps1

# Write a function that does an SPF lookup and returns the number og "include" lookups there is
# The function should be recursive, so it should be able to follow the includes in the SPF record and count them as well

# The function should also be able to handle the limit of 10 lookups, so it should stop if it reaches that limit
# The function should return the number of lookups and the SPF record itself
# The function should also be able to handle the case where the SPF record is empty or does not exist
# The function should also be able to handle the case where the SPF record is not a valid SPF record
# The function should also be able to handle the case where the SPF record is not a valid DNS record

function Get-SpfLookupCount {
    param (
        [string]$Domain
    )

    # Helper function to perform DNS TXT record lookup
    function Get-TxtRecord {
        param ([string]$Domain)
        try {
            $records = Resolve-DnsName -Name $Domain -Type TXT -ErrorAction Stop -Server 1.1.1.1
            return $records | Where-Object { $_.Strings -match "^v=spf1" } | Select-Object -ExpandProperty Strings
        } catch {
            Write-Verbose "Failed to resolve TXT record for domain: $Domain"
            return $null
        }
    }

    # Recursive function to count SPF includes
    function Count-Includes {
        param (
            [string]$SpfRecord,
            [int]$CurrentCount
        )

        if (-not $SpfRecord) {
            Write-Verbose "SPF record is empty or invalid."
            return $CurrentCount
        }

        $includes = ($SpfRecord -split ' ') | Where-Object { $_ -like "include:*" }
        foreach ($include in $includes) {
            $includedDomain = $include -replace "include:", ""
            Write-Verbose "Processing include for domain: $includedDomain"
            $includedSpfRecord = Get-TxtRecord -Domain $includedDomain
            if ($includedSpfRecord) {
                $CurrentCount = Count-Includes -SpfRecord $includedSpfRecord -CurrentCount ($CurrentCount + 1) -MaxLookups $MaxLookups
            } else {
                Write-Verbose "No valid SPF record found for included domain: $includedDomain"
            }
        }

        return $CurrentCount
    }

    $spfRecord = Get-TxtRecord -Domain $Domain
    if (-not $spfRecord) {
        Write-Output @{
            Lookups = 0
            SpfRecord = $null
            Message = "No valid SPF record found for domain: $Domain"
        }
        return
    }

    $lookupCount = Count-Includes -SpfRecord $spfRecord -CurrentCount 0 -MaxLookups $MaxLookups
    if ($lookupCount -gt 10) {
        $spfCountError = "Exceeded SPF lookup limit of 10."
    }

    return @{
        Lookups = $lookupCount
        SpfRecord = $spfRecord
        Message = "SPF lookup completed."
        Error = $spfCountError
    }
}