Retrieve Azure Tenant Id using PowerShell

Reading Time: < 1 minute

CodeSnippets #1

I have an idea to do a series of short blog posts over the year with helpful PowerShell functions, SQL code or problems I’ve encountered. The kind of thing I wouldn’t bother writing about as it would barely hit 200 words. I’d love some feedback on whether these “snippets” are helpful.

This is a very handy little function that I refer to on a regular basis when working with Azure and Power BI in PowerShell. The purpose of the function is to quickly retrieve the tenant Id of any Azure tenant based on the provided parameter. The user can provide a domain name or a valid email address. The function queries Azure anonymously so there’s no requirement to login first.

You can also find this up on my Github. PRs are always welcome!


Retrieve a domain's Azure tenant ID anonymously

This function will anonymously retrieve a domain's Azure tenant ID using a provided email containing the target domain or a domain itself.

The full domain of the Azure tenant.

An email or user account that contains the domain of the Azure tenant

Get-AzureTenantID -Domain

Get-AzureTenantID -Email

General notes

function Get-AzureTenantId{

        [ValidateScript({$_ -notmatch "@"})]

        [ValidateScript({$_ -match "@"})]

            Write-Verbose 'Domain provided.'
        elseif ($email) {
            Write-Verbose 'Split the string on the username to get the Domain.'
            $domain = $email.Split("@")[1]
            Write-Warning 'You must provide a valid Domain or User email to proceed.'

        Write-Verbose 'Query Azure anonymously.'
        $tenantId = (Invoke-WebRequest -UseBasicParsing$($Domain)/.well-known/openid-configuration|ConvertFrom-Json).token_endpoint.Split('/')[3]

        return $tenantId


You may also like...

3 Responses

  1. Dana Epp says:

    OK, so what happens when you use an email address from gmail or outlook? I have But getting the Azure tenant ID for is NOT the same as mine, which is

    • Craig says:

      Hey Dana, So I had an extra chunk of code to handle that situation but I can’t locate it just now. I’ll try to dig this out but it is possible with the function. Until then, you can pull the function apart and pass your email through as the address and it should return the correct tenantID. Let me know how you get on. Ta, Craig

  2. Oh nice I like it Craig! 🙂

Leave a Reply