I need assistance fixing or modifying the code below to find the name of the Resource Group where the specific Azure AD / Entra ID B2C tenant object is located by going through all of my Azure Subscriptions.
The input is based on the GUID or TenantName where possible.
This code below always ends up in 'Unknown' as the result:
function Get-ResourceGroup {
param (
[Parameter(Mandatory)]
[string]$TenantId
)
# Ensure authentication
try {
$account = Get-AzContext
if (-not $account -or $account.Tenant.Id -ne $TenantId) {
Write-Verbose "Authenticating to Azure..."
Connect-AzAccount -TenantId $TenantId -UseDeviceAuthentication
}
} catch {
Write-Error "Failed to authenticate. Ensure you have access to tenant: $TenantId"
return "Unknown"
}
# Get subscriptions in the correct tenant
$subscriptions = Get-AzSubscription -TenantId $TenantId
foreach ($sub in $subscriptions) {
Write-Verbose "`nChecking Subscription: $($sub.Id) ($($sub.Name))"
# Set context
Set-AzContext -SubscriptionId $sub.Id -ErrorAction SilentlyContinue | Out-Null
# Retrieve the B2C resource
$resource = Get-AzResource -ResourceType "Microsoft.AzureActiveDirectory/b2cDirectories" -ErrorAction SilentlyContinue |
Where-Object { $_.Properties.TenantId -eq $TenantId -and $_.SubscriptionId -eq $sub.Id }
if ($resource) {
Write-Verbose "`tFound Resource Group: $($resource.ResourceGroupName) in Subscription $($sub.Id)"
return $resource.ResourceGroupName
}
}
Write-Warning "No matching resource found for TenantId: $TenantId"
return "Unknown"
}
Get-ResourceGroup -TenantId '7307f3e9-f54d-4654-be58-ca823d4cfd91' -Verbose
Any help would be appreciated.
This is really easy to accomplish with a KQL query to Azure Resource Graph, you can query it using Search-AzGraph
from the Az.ResourceGraph
Module.
function Get-ResourceGroup {
param(
[Parameter(Mandatory)]
[string] $TenantId
)
$result = Search-AzGraph "
resources
| where ['type'] == 'microsoft.azureactivedirectory/b2cdirectories'
and properties.tenantId == '$TenantId'
| project subscriptionId, resourceGroup"
if ($result.Data.Count -eq 0) {
Write-Warning "No matching resource found for TenantId: $TenantId"
return "Unknown"
}
Write-Verbose "Found Resource Group: $($result.resourceGroup) in Subscription $($result.subscriptionId)"
$result.Data.resourceGroup
}
Get-ResourceGroup 7307f3e9-f54d-4654-be58-ca823d4cfd91 -Verbose