M365-TestUserEmail.ps1

function M365-TestUserEmail {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$EmailAddress,
        
        [Parameter(Mandatory = $true)]
        [string]$ClientId,  # Azure AD Application Client ID
        
        [Parameter(Mandatory = $true)]
        [string]$ClientSecret,  # Azure AD Application Client Secret
        
        [Parameter(Mandatory = $true)]
        [string]$TenantId  # Azure AD Tenant ID
    )

    try {
        # Authenticate using the Azure AD Application Client Credentials
        $body = @{
            client_id     = $ClientId
            scope         = "https://graph.microsoft.com/.default"
            client_secret = $ClientSecret
            grant_type    = "client_credentials"
        }

        $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method POST -ContentType "application/x-www-form-urlencoded" -Body $body

        # Use the access token to call the Microsoft Graph API and check if the user exists
        $accessToken = $tokenResponse.access_token
        $apiUrl = "https://graph.microsoft.com/v1.0/users"

        $userExists = Invoke-RestMethod -Uri "$apiUrl/\$filter=mail eq '$EmailAddress'" -Headers @{Authorization = "Bearer $accessToken"} -Method GET

        if ($userExists.value.Count -gt 0) {
            Write-Host "User with email address '$EmailAddress' exists in Microsoft 365."
        } else {
            Write-Host "User with email address '$EmailAddress' does not exist in Microsoft 365."
        }
    } catch {
        Write-Host "Error: $_"
    }
}

# Example usage:
# Test-M365UserEmailAddress -EmailAddress "user@example.com" -ClientId "your_client_id" -ClientSecret "your_client_secret" -TenantId "your_tenant_id"