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!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<# .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 } } |
Oh nice I like it Craig! 🙂