How to get the details like Tenant and Subscription that user belongs to?

krishna572 886 Reputation points
2023-03-31T03:39:16.56+00:00

Could anyone please provide me the Azure PowerShell commands for checking the user belongs to specific tenant and specific subscription?

I tried googling it but didn't find the appropriate command for this requirement.

https://learn.microsoft.com/en-us/powershell/module/azuread/get-azureaduser?view=azureadps-2.0

but this command will not provide tenant details or subscription details

Azure Cloud Services
Azure Cloud Services
An Azure platform as a service offer that is used to deploy web and cloud applications.
769 questions
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Sedat SALMAN 14,180 Reputation points MVP
    2023-03-31T04:03:34.8533333+00:00

    you can use the following

    note: please update according to your requirements

    
    # Install AzureAD and Az modules if not already installed
    # Install-Module -Name AzureAD
    # Install-Module -Name Az
    
    # Authenticate with the tenant by providing the tenant domain
    $tenantDomain = "yourtenant.onmicrosoft.com"
    Connect-AzureAD -TenantDomain $tenantDomain
    
    # Get tenant ID
    $tenant = Get-AzureADTenantDetail
    $tenantId = $tenant.ObjectId
    Write-Host "Tenant ID: $tenantId"
    
    # Authenticate with Azure using tenant ID
    Connect-AzAccount -Tenant $tenantId
    
    # Specify user and subscription
    $userEmail = "user@example.com"
    $subscriptionId = "your_subscription_id"
    
    # Get user details
    $user = Get-AzureADUser -SearchString $userEmail
    if (!$user) {
        Write-Host "User not found in the specified tenant"
    } else {
        Write-Host "User found in the specified tenant"
    
        # Get subscriptions associated with the user
        $subscriptions = Get-AzSubscription -User $user.ObjectId
    
        # Check if user belongs to the specified subscription
        $userSubscription = $subscriptions | Where-Object { $_.Id -eq $subscriptionId }
        if ($userSubscription) {
            Write-Host "User belongs to the specified subscription"
        } else {
            Write-Host "User does not belong to the specified subscription"
        }
    }
    
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.