Retrieve Azure Tenant Id using PowerShell
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!
Enjoy!
<# .SYNOPSIS Retrieve a domain's Azure tenant ID anonymously .DESCRIPTION This function will anonymously retrieve a domain's Azure tenant ID using a provided email containing the target domain or a domain itself. .PARAMETER Domain The full domain of the Azure tenant. .PARAMETER Email An email or user account that contains the domain of the Azure tenant .EXAMPLE Get-AzureTenantID -Domain craigporteous.com Get-AzureTenantID -Email craig@craigporteous.com .NOTES General notes #> function Get-AzureTenantId{ [CmdletBinding()] param ( [ValidateScript({$_ -notmatch "@"})] [string] $domain, [ValidateScript({$_ -match "@"})] [string] $email ) Process{ if($domain){ Write-Verbose 'Domain provided.' } elseif ($email) { Write-Verbose 'Split the string on the username to get the Domain.' $domain = $email.Split("@")[1] } else{ throw Write-Warning 'You must provide a valid Domain or User email to proceed.' } Write-Verbose 'Query Azure anonymously.' $tenantId = (Invoke-WebRequest -UseBasicParsing https://login.windows.net/$($Domain)/.well-known/openid-configuration|ConvertFrom-Json).token_endpoint.Split('/')[3] return $tenantId } }
OK, so what happens when you use an email address from gmail or outlook? I have dana@outlook.com. But getting the Azure tenant ID for outlook.onmicrosoft.com is NOT the same as mine, which is danaoutlook.onmicrosoft.com.
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 onmicrosoft.com address and it should return the correct tenantID. Let me know how you get on. Ta, Craig
Oh nice I like it Craig! 🙂