Skip to content

Commit f772db1

Browse files
authored
Create Get-TenantIdFromSubscriptionId.ps1
For future use
1 parent 270b54c commit f772db1

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function Get-TenantIdFromSubscriptionId {
2+
param (
3+
[Parameter(Mandatory = $true)]
4+
[string]$SubscriptionId
5+
)
6+
7+
# Full credit goes to Jos Lieben
8+
# https://www.lieben.nu/liebensraum/2020/08/get-tenant-id-using-azure-subscription-id/
9+
10+
try {
11+
Invoke-WebRequest -UseBasicParsing -Uri "https://management.azure.com/subscriptions/$($SubscriptionId)`?api-version=2015-01-01" -ErrorAction Stop
12+
} catch {
13+
# The error response contains the WWW-Authenticate header with the tenant ID
14+
$response = $_.Exception.Response
15+
}
16+
17+
# Extract tenant ID from WWW-Authenticate header
18+
$authHeader = $response.Headers.GetValues("WWW-Authenticate")[0]
19+
20+
# Use regex to extract the tenant ID
21+
if ($authHeader -match "login\.windows\.net\/([0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12})") {
22+
return $matches[1]
23+
}
24+
25+
return $null
26+
}

0 commit comments

Comments
 (0)