Tuesday, 7 October 2025

Get-Unique Email Address

 function Get-UniqueEmail {

    param (
            [string]$baseEmailPrefix,
            [string]$domain
        )
  

   # Step 1: Check if the base prefix ends with a number
    if ($baseEmailPrefix -match '^(.*?)(.)(\d+)$') {
     # Step 2:  Remove the character before the number
            $prefix = $matches[1] + $matches[2]+ $matches[3]
        } else {
            $prefix = $baseEmailPrefix
        }

    # Step 3: Check if mailbox is available
    if (!(Get-Recipient $emailToCheck -ErrorAction SilentlyContinue)) {
        Write-Host "Email available: $emailToCheck"
        return $emailToCheck
        }
    # Step 4: Loop to find unique email
        $number = 1
    do {
            $newPrefix = "$trimmedPrefix$number"
        # If new prefix exceeds 50 characters, remove character before number
            if ($newPrefix.Length -gt 50) {
                if ($newPrefix -match '^(.*?)(.)(\d+)$') {
                        $newPrefix = $matches[1] + $matches[3]
                    }
            }
    # Trim again to 50 characters
            $finalPrefix = $newPrefix.Substring(0, [Math]::Min(50, $newPrefix.Length))
            $newEmail = "$finalPrefix@$domain"
            Write-Host "Trying email: $newEmail"
            $recipient = Get-Recipient $newEmail -ErrorAction SilentlyContinue
            $number++
        } while ($recipient)
        Write-Host "Unique email found: $newEmail"
        return $newEmail
}


$basePrefix = "TestEmailIndia"
$domain = "contoso.com"
$uniqueEmail = Get-UniqueEmail -baseEmailPrefix $basePrefix -domain $domain
Write-Host "Available Email: $uniqueEmail"