Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Created July 8, 2021 15:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinGrote/e8b51f0845813b933035c40a5390707e to your computer and use it in GitHub Desktop.
Save JustinGrote/e8b51f0845813b933035c40a5390707e to your computer and use it in GitHub Desktop.
Get Azure Tenant ID from Name
function Get-AzTenantId {
<#
.SYNOPSIS
Resolves the tenant ID for a specified name.
.OUTPUTS
System.Guid. The Tenant ID of the specified name
#>
[CmdletBinding()]
param(
#The tenant string you wish to resolve. Examples include: mydomain.com, myorg.onmicrosoft.com
[Parameter(Mandatory,ValueFromPipeline)][String]$Tenant
)
process {
if ([Uri]::CheckHostName($Tenant) -ne [UriHostNameType]::Dns) {
Write-Error "$Tenant is not a valid DNS name. Please specify something like mydomain.com or myorg.onmicrosoft.com"
return
}
try {
$endpoint = (Invoke-RestMethod -UseBasicParsing -ErrorAction Stop -Uri "https://login.microsoftonline.com/$Tenant/v2.0/.well-known/openid-configuration").authorization_endpoint
} catch [Microsoft.PowerShell.Commands.HttpResponseException] {
if ($_.FullyQualifiedErrorId -eq 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand') {
[PSCustomObject]$errorResponse = $PSItem.ErrorDetails.Message | ConvertFrom-Json
Write-Error ("{0}: {1}" -f $errorResponse.error, $errorResponse.error_description)
return
} else {
Write-Error -ErrorRecord $PSItem
return
}
}
$guidRegex = '(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})'
if ($endpoint -notmatch $guidRegex) {
Write-Error "Query succeeded but unable to resolve an Id for $Tenant. This is probably a bug."
return
}
return [guid]::Parse($matches[1])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment