Get tenant ID using Azure Subscription ID

For a customer use case in an Azure Marketplace Managed Application scenario, I needed the ability to translate the (customers’) Azure Subscription ID (which is known to the publishing tenant) to a tenant ID. Using Get-AzSubscription, Lighthouse subscriptions don’t show the true tenant ID of the other tenant, but only show your own tenant ID.

The following PS function can retrieve the tenant ID for you (without authentication):

function get-tenantIdFromSubscriptionID($subId){
    $response = try {(Invoke-WebRequest -UseBasicParsing -Uri "https://management.azure.com/subscriptions/$($subId)?api-version=2015-01-01" -ErrorAction Stop).BaseResponse} catch { $_.Exception.Response } 
    $stringHeader = $response.Headers.ToString()
    return($stringHeader.SubString($stringHeader.IndexOf("login.windows.net")+18,36))
}
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Manni Pauls
Manni Pauls
2 months ago

This is really cool. Using an error msg from the unauthorized call and pull out the tenant ID. Well done 🙂 !!