← AZURE / ENTRA TOOLBOX

READ-ONLY / QUERY LOAD + LOCAL EXPORT

Report visible Entra group relationships

Review one selected group’s visible owners and either direct or flattened transitive membership. The relationship rows preserve object types and visibility context; they are not an effective-access calculation.

REVIEW CANDIDATE · LIVE TENANT VALIDATION PENDING

Verification is offline and mocked—not a successful connection to your tenant. Review the complete source, permission scope, and output handling before a small authorized test. Read-only does not mean risk-free.

RUNTIME
PowerShell 7; Microsoft.Graph.Authentication installed manually
CONNECTION
Explicit tenant · delegated identity · Global cloud · Process context
DELEGATED SCOPES
GroupMember.Read.All (delegated)
DIRECTORY WRITES
None requested by these tools
OUTPUT
Visible owners and members in a report envelope; optional local CSV
WEBSITE ACCESS
No tenant connection, credential form, or report upload

Before running anything

  1. Use a trusted PowerShell 7 environment. Obtain and review Microsoft.Graph.Authentication through your organization’s approved process. These scripts do not install modules, provision an app registration, or modify tenant settings.
  2. Choose the intended tenant ID from a trusted source. Confirm the operator account and the smallest purpose needed. Read the source locally; do not paste credentials or tokens into this website.
  3. Use only the delegated scopes listed above. Administrator consent is required for Application.Read.All, User.Read.All and GroupMember.Read.All; User.ReadBasic.All is subject to tenant consent policy. Existing approved consent may already cover the required scopes. A Microsoft sign-in or consent screen is not permission to bypass your organization’s approval process. These scripts do not grant admin consent or change consent policy; stop if the approved permissions are unavailable.
  4. Start with a selected test identity or group. Directory reads can expose confidential data and create query load. Review local transcript, terminal-history, and export policies before running.
# Inspect the local environment; this does not install anything.
$PSVersionTable.PSVersion
Get-Module Microsoft.Graph.Authentication -ListAvailable

Start deliberately, then inspect the result.

All IDs, accounts, and names below are fictional placeholders. Replace them with explicitly authorized values. Download the connection helper alongside the reader and use the same PowerShell process.

# FICTIONAL VALUES. Connect in this same PowerShell process first.
.\Connect-SwpEntra.ps1 -TenantId '11111111-1111-1111-1111-111111111111' -Purpose Groups -ExpectedAccount 'operator@example.invalid'

# Direct is the default; name it explicitly while learning the tool.
$report = .\Get-SwpEntraGroupReport.ps1 -TenantId '11111111-1111-1111-1111-111111111111' -GroupId '22222222-2222-2222-2222-222222222222' -Membership Direct
$report.Owners
$report.Members

# Flattened transitive membership is a different view, not a nesting-path report.
.\Get-SwpEntraGroupReport.ps1 -TenantId '11111111-1111-1111-1111-111111111111' -GroupId '22222222-2222-2222-2222-222222222222' -Membership Transitive -MaxRecords 100 -MaxPages 5

# Optional export to an existing, access-controlled folder.
.\Get-SwpEntraGroupReport.ps1 -TenantId '11111111-1111-1111-1111-111111111111' -GroupId '22222222-2222-2222-2222-222222222222' -Membership Direct -CsvDirectory '.\Reports'

Readers verify the expected tenant and connection before querying. MaxPages, MaxRecords, and MaxRetries are explicit bounds, not a promise of a complete snapshot. Defaults are 20 pages, 1,000 records, and 3 retries. Avoid broad filters or large groups until you understand the impact.

What the output does—and does not—establish.

  • Direct membership describes immediate relationships. Transitive membership is a flattened set of reachable members, not the nesting paths or an explanation of which group granted access. Owners are reported separately; transitive membership does not make someone an owner.
  • Members can be mixed directory object types. Do not assume every row is a user, or discard a row just because a user principal name is absent. Limited-information rows may contain only an object ID and type.
  • Microsoft Graph v1.0 has documented service-principal omissions in both group member and owner lists. These reports must not be described as a complete service-principal or tenant inventory.
  • Owner retrieval is not supported for groups created in Exchange, distribution groups, or groups synchronized from on-premises AD. A missing owner list does not prove an owner does not exist elsewhere.
  • Hidden membership and protected resource details may require additional permissions and directory roles. This preview does not automatically request Member.Read.Hidden or additional type-specific permissions. A shorter or empty result is not proof of complete visibility.
  • The script does not infer nested authorization, application access, Azure RBAC, active PIM roles, or successful sign-ins from group membership.

Complete source. One version.

The displayed source, clipboard copy, download, and GitHub link use the same published script version. Nothing runs when you view or copy this page.

Get-SwpEntraGroupReport.ps1POWERSHELL 7 / REVIEW PREVIEW
#requires -Version 7.0
<#
.SYNOPSIS
Read one group's visible owners and direct OR flat transitive members.
.DESCRIPTION
Requires Microsoft.Graph.Authentication, explicit TenantId/GroupId and delegated
Global/Process context with GroupMember.Read.All. No connection, installation,
write requests, roles/PIM, or permission escalation is performed.
IMPORTANT: v1.0 direct members and owners have documented service-principal
omissions. This report is coverage-limited even when every returned page is read.
It is NOT a full inventory, access certification, or proof of no members/owners.
The documented direct-member beta/$expand workaround is not silently applied:
expanded collections can truncate and beta has different support expectations.
Transitive is a flat list of nested members, not a path/provenance report.
Hidden membership additionally requires Member.Read.Hidden AND sufficient user
rights; this script never adds that permission. Owners may be unavailable for
Exchange-created, distribution or on-premises-synced groups. Known unsupported
owner sources are labeled unavailable rather than reported as having no owners.
Optional CSV: timestamped new file in your chosen filesystem directory, formula-like cells neutralized, [null]
marks unavailable values. All requested calls must finish before output/export.
.EXAMPLE
./Get-SwpEntraGroupReport.ps1 -TenantId '11111111-1111-4111-8111-111111111111' -GroupId '22222222-2222-4222-8222-222222222222' -Membership Direct
.NOTES
Choose a protected export directory; filesystem paths may be network-mounted or
cloud-synced. CSV contains directory data and must be handled accordingly.
MaxRetries bounds this script's loop; the Graph SDK may apply its own retry policy.
Sources: learn.microsoft.com/graph/api/group-list-members and group-list-owners
(v1.0). No beta or complete-inventory claim. Live-tenant validation pending.
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory)][guid]$GroupId,
    [ValidateSet('Direct','Transitive')][string]$Membership = 'Direct',

    [Parameter(Mandatory)][guid]$TenantId,
    [ValidateRange(1,100)][int]$MaxPages = 20,
    [ValidateRange(1,10000)][int]$MaxRecords = 1000,
    [ValidateRange(0,5)][int]$MaxRetries = 3,
    [string]$CsvDirectory
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
function Get-SwpValue {
    param($Object, [string]$Name)
    if ($null -eq $Object) { return $null }
    if ($Object -is [System.Collections.IDictionary]) { return ,($Object[$Name]) }
    $property = $Object.PSObject.Properties[$Name]
    if ($null -ne $property) { return ,($property.Value) }
    return $null
}
function Assert-SwpContext {
    param([string[]]$RequiredScopes)
    if (-not (Get-Command Get-MgContext -ErrorAction SilentlyContinue)) {
        throw 'Microsoft.Graph.Authentication is required. Review and install it separately; this script never installs modules.'
    }
    $context = Get-MgContext
    if ($null -eq $context) { throw 'No Graph context. First run Connect-SwpEntra.ps1 for the explicit tenant and purpose.' }
    if ([string](Get-SwpValue $context 'TenantId') -ine $TenantId.ToString()) { throw 'Wrong tenant context. No Graph request was made. Disconnect explicitly and reconnect to the intended tenant.' }
    if ([string](Get-SwpValue $context 'AuthType') -ine 'Delegated' -or [string]::IsNullOrWhiteSpace([string](Get-SwpValue $context 'Account'))) { throw 'A delegated signed-in account is required; application-only access is outside this script.' }
    if ([string](Get-SwpValue $context 'Environment') -ine 'Global') { throw 'Only the Global Microsoft Graph cloud is supported by this artifact.' }
    if ([string](Get-SwpValue $context 'ContextScope') -ine 'Process') { throw 'Use a Process-scoped Graph connection; persistent CurrentUser context is not accepted.' }
    $actualScopes = Get-SwpValue $context 'Scopes'
    foreach ($scope in $RequiredScopes) { if ($scope -notin $actualScopes) { throw "Missing delegated scope $scope. Reconnect explicitly for the required purpose; permissions are not broadened automatically." } }
    return $context
}

function Assert-SwpGraphUri {
    param([string]$Address, [string]$ExpectedPath = '')
    $uri = $null
    if (-not [uri]::TryCreate($Address, [UriKind]::Absolute, [ref]$uri) -or $uri.Scheme -cne 'https' -or $uri.Host -ine 'graph.microsoft.com' -or $uri.Port -ne 443 -or $uri.UserInfo -or $uri.Fragment -or -not $uri.AbsolutePath.StartsWith('/v1.0/', [StringComparison]::Ordinal)) {
        throw 'Rejected Graph URL: only HTTPS graph.microsoft.com/v1.0 with no credentials or fragment is permitted.'
    }
    if ($ExpectedPath -and $uri.AbsolutePath -cne $ExpectedPath) { throw 'Rejected pagination URL: the collection path changed.' }
}
function Invoke-SwpGet {
    param([string]$Address)
    Assert-SwpGraphUri $Address
    for ($attempt = 0; $attempt -le $MaxRetries; $attempt++) {
        # Recheck before every call: another script in this process must not switch tenants unnoticed.
        $verifiedContext = Assert-SwpContext $script:SwpRequiredScopes
        if ([string](Get-SwpValue $verifiedContext 'Account') -ine $script:SwpInitialAccount -or [string](Get-SwpValue $verifiedContext 'ClientId') -ine $script:SwpInitialClientId) { throw 'The Graph account or client changed during this report. No mixed-identity report was produced.' }
        try { return Invoke-MgGraphRequest -Method GET -Uri $Address -OutputType PSObject -ErrorAction Stop }
        catch {
            $response = Get-SwpValue $_.Exception 'Response'
            $rawStatus = Get-SwpValue $response 'StatusCode'
            if ($null -eq $rawStatus) { $rawStatus = Get-SwpValue $_.Exception 'ResponseStatusCode' }
            $status = 0
            if ($null -ne $rawStatus) { try { $status = [int]$rawStatus } catch { $status = 0 } }
            if ($status -notin @(429, 503) -or $attempt -ge $MaxRetries) { throw }
            $delay = [int][Math]::Pow(2, $attempt + 1)
            $headers = Get-SwpValue $response 'Headers'
            $retry = Get-SwpValue $headers 'Retry-After'
            if ($retry -is [array]) { $retry = $retry[0] }
            $typedRetry = Get-SwpValue $headers 'RetryAfter'
            if ($null -ne $retry) {
                $seconds = 0
                $retryDate = [DateTimeOffset]::MinValue
                if ([int]::TryParse([string]$retry, [ref]$seconds)) { $delay = [Math]::Max(0, $seconds) }
                elseif ([DateTimeOffset]::TryParse([string]$retry, [ref]$retryDate)) { $delay = [int][Math]::Ceiling([Math]::Max(0, ($retryDate - [DateTimeOffset]::UtcNow).TotalSeconds)) }
                else { throw 'Unrecognized Retry-After value. Stopping rather than guessing a retry deadline.' }
            } elseif ($null -ne $typedRetry) {
                $delta = Get-SwpValue $typedRetry 'Delta'
                $date = Get-SwpValue $typedRetry 'Date'
                if ($null -ne $delta) { $delay = [int][Math]::Ceiling($delta.TotalSeconds) }
                elseif ($null -ne $date) { $delay = [int][Math]::Ceiling([Math]::Max(0, ($date - [DateTimeOffset]::UtcNow).TotalSeconds)) }
            }
            if ($delay -gt 60) { throw 'Retry-After exceeds the 60-second per-retry budget. No partial report was produced; retry later.' }
            Start-Sleep -Seconds ([Math]::Max(0, $delay))
        }
    }
}
function Get-SwpPages {
    param([string]$Address)
    $expectedPath = ([uri]$Address).AbsolutePath
    $seen = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
    $items = [System.Collections.Generic.List[object]]::new()
    $next = $Address
    $pageCount = 0
    while (-not [string]::IsNullOrEmpty($next)) {
        Assert-SwpGraphUri $next $expectedPath
        if (-not $seen.Add($next)) { throw 'Repeated pagination URL: refusing an incomplete looped report.' }
        if ($pageCount -ge $MaxPages) { throw 'Page limit exceeded. No partial report/CSV was produced. Narrow the query or explicitly review a higher bound.' }
        $page = Invoke-SwpGet $next
        $values = Get-SwpValue $page 'value'
        if ($null -eq $values -or $values -is [string] -or $values -isnot [System.Collections.IEnumerable]) { throw 'Malformed Graph collection response: no value array.' }
        foreach ($item in $values) {
            if ([string]::IsNullOrWhiteSpace([string](Get-SwpValue $item 'id'))) { throw 'Graph returned an object without an ID; report aborted rather than dropping it.' }
            if ($items.Count -ge $MaxRecords) { throw 'Record limit exceeded. No partial report/CSV was produced.' }
            [void]$items.Add($item)
        }
        $pageCount++
        $next = [string](Get-SwpValue $page '@odata.nextLink')
    }
    return ,($items.ToArray())
}
function ConvertTo-SwpCsvCell {
    param($Value)
    if ($null -eq $Value) { return '[null]' }
    $text = [string]$Value
    # Neutralize formula prefixes even behind spaces/control characters. Raw output objects remain unchanged.
    if ($text -match '^[\s\x00-\x1f]*[=+\-@]' -or $text -match '^[\t\r\n]') { return "'" + $text }
    return $text
}
function Export-SwpCsv {
    param([object[]]$Rows, [string]$Prefix)
    if ([string]::IsNullOrWhiteSpace($CsvDirectory)) { return $null }
    $directory = Get-Item -LiteralPath $CsvDirectory -ErrorAction Stop
    if (-not $directory.PSIsContainer -or $directory.PSProvider.Name -ne 'FileSystem') { throw 'CsvDirectory must be an existing filesystem directory.' }
    $stamp = [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')
    $leaf = $Prefix + '-' + $stamp + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8) + '.csv'
    $path = Join-Path $directory.FullName $leaf
    $safeRows = foreach ($row in $Rows) {
        $safe = [ordered]@{}
        foreach ($property in $row.PSObject.Properties) { $safe[$property.Name] = ConvertTo-SwpCsvCell $property.Value }
        [pscustomobject]$safe
    }
    $lines = @($safeRows | ConvertTo-Csv -NoTypeInformation)
    Write-SwpCsvFile -Path $path -Lines $lines
}
function Write-SwpCsvFile {
    param([string]$Path, [string[]]$Lines)
    $stream = $null
    $writer = $null
    $created = $false
    try {
        # CreateNew is the overwrite guarantee, not a vulnerable Test-Path-then-write check.
        $stream = [IO.File]::Open($path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)
        $created = $true
        $writer = [IO.StreamWriter]::new($stream, [Text.UTF8Encoding]::new($false))
        foreach ($line in $lines) { $writer.WriteLine($line) }
        $writer.Flush()
        $writer.Dispose(); $writer = $null; $stream = $null
        return $path
    } catch {
        $failure = $_
        # Dispose may itself fail after a disk/flush error; still attempt partial-file cleanup.
        try { if ($null -ne $writer) { $writer.Dispose() } elseif ($null -ne $stream) { $stream.Dispose() } } catch { }
        try { if ($created -and [IO.File]::Exists($path)) { [IO.File]::Delete($path) } }
        catch { throw "CSV export failed and partial-file cleanup also failed at '$path'. Remove the partial file explicitly. Original failure: $($failure.Exception.Message)" }
        throw $failure
    }
}

if ($TenantId -eq [guid]::Empty -or $GroupId -eq [guid]::Empty) { throw 'TenantId and GroupId cannot be empty.' }
$script:SwpRequiredScopes = @('GroupMember.Read.All')
$context = Assert-SwpContext $script:SwpRequiredScopes
$script:SwpInitialAccount = [string](Get-SwpValue $context 'Account')
$script:SwpInitialClientId = [string](Get-SwpValue $context 'ClientId')
if (-not (Get-Command Invoke-MgGraphRequest -ErrorAction SilentlyContinue)) { throw 'Invoke-MgGraphRequest is required from Microsoft.Graph.Authentication.' }
$base = 'https://graph.microsoft.com/v1.0/groups/' + $GroupId.ToString()
$group = Invoke-SwpGet ($base + '?$select=id,displayName,groupTypes,mailEnabled,securityEnabled,onPremisesSyncEnabled,visibility')
if ([string](Get-SwpValue $group 'id') -ine $GroupId.ToString()) { throw 'Group response ID does not match the requested group.' }
if ([string](Get-SwpValue $group 'visibility') -ieq 'HiddenMembership' -and 'Member.Read.Hidden' -notin (Get-SwpValue $context 'Scopes')) { throw 'Hidden membership needs separately approved Member.Read.Hidden and appropriate user rights. No membership report was produced.' }
$groupTypes = Get-SwpValue $group 'groupTypes'
$ownersUnavailable = (Get-SwpValue $group 'onPremisesSyncEnabled') -eq $true -or ((Get-SwpValue $group 'mailEnabled') -eq $true -and 'Unified' -notin $groupTypes)
$ownerStatus = 'Visible v1.0 owners only; service-principal owners can be omitted. Exchange-created sources may not support this relationship.'
$ownerRaw = @()
if ($ownersUnavailable) { $ownerStatus = 'Unavailable for this on-premises-synced or non-Unified mail-enabled source; an empty Owners array is NOT evidence of no owners.' }
else { $ownerRaw = Get-SwpPages ($base + '/owners?$top=100') }
$relation = if ($Membership -eq 'Direct') { 'members' } else { 'transitiveMembers' }
$memberRaw = Get-SwpPages ($base + '/' + $relation + '?$top=100')
function ConvertTo-SwpDirectoryObject {
    param($Object)
    $name = Get-SwpValue $Object 'displayName'
    $type = Get-SwpValue $Object '@odata.type'
    [pscustomobject]@{ Id=Get-SwpValue $Object 'id'; ObjectType=if ($type) { $type } else { '[unknown type]' }; DisplayName=$name; UserPrincipalName=Get-SwpValue $Object 'userPrincipalName'; Mail=Get-SwpValue $Object 'mail'; Visibility=if ($null -eq $name) { 'Name unavailable; possibly permission-limited' } else { 'Returned fields only' } }
}
$owners = @($ownerRaw | ForEach-Object { ConvertTo-SwpDirectoryObject $_ })
$members = @($memberRaw | ForEach-Object { ConvertTo-SwpDirectoryObject $_ })
$coverage = 'Coverage-limited visible v1.0 results, not a complete inventory. Owners can omit service principals; Direct members also have a documented service-principal omission. Transitive results are flat, not membership paths. Hidden/other object fields depend on permissions.'
$retrieved = [DateTime]::UtcNow.ToString('o')
$rows = [System.Collections.Generic.List[object]]::new()
[void]$rows.Add([pscustomobject]@{ RecordType='Summary'; TenantId=$TenantId.ToString(); GroupId=$GroupId.ToString(); MembershipMode=$Membership; RetrievedAtUtc=$retrieved; Coverage=$coverage; OwnerCoverage=$ownerStatus; Count=$members.Count; Id=$null; ObjectType=$null; DisplayName=Get-SwpValue $group 'displayName'; UserPrincipalName=$null; Mail=$null; Visibility=$null })
foreach ($kind in @('Owner','Member')) {
    $objects = if ($kind -eq 'Owner') { $owners } else { $members }
    foreach ($item in $objects) { [void]$rows.Add([pscustomobject]@{ RecordType=$kind; TenantId=$TenantId.ToString(); GroupId=$GroupId.ToString(); MembershipMode=$Membership; RetrievedAtUtc=$retrieved; Coverage=$coverage; OwnerCoverage=$ownerStatus; Count=$null; Id=$item.Id; ObjectType=$item.ObjectType; DisplayName=$item.DisplayName; UserPrincipalName=$item.UserPrincipalName; Mail=$item.Mail; Visibility=$item.Visibility }) }
}
$csvPath = Export-SwpCsv $rows.ToArray() 'ShellWePlay-EntraGroup'
[pscustomobject]@{ TenantId=$TenantId.ToString(); Account=Get-SwpValue $context 'Account'; GroupId=$GroupId.ToString(); GroupDisplayName=Get-SwpValue $group 'displayName'; MembershipMode=$Membership; RetrievedAtUtc=$retrieved; Coverage=$coverage; OwnerCoverage=$ownerStatus; OwnerCount=$owners.Count; MemberCount=$members.Count; Owners=$owners; Members=$members; CsvPath=$csvPath }

Local output is still sensitive.

These tools do not send results to ShellWePlay. When a reader’s CsvDirectory option is used, the export is written on the machine running PowerShell—not in the browser. Choose an existing access-controlled folder. Keep tenant IDs, account identifiers, memberships, and ownership information out of public shares and tickets unless authorized.

Do not treat CSV as harmless text: review the source’s export handling and your spreadsheet tooling. A successfully written file is not proof of complete directory visibility. Keep the coverage limitations with the result.

End your dedicated session deliberately.

When you are finished with the Graph session you opened for this work, disconnect it explicitly. Do not disconnect another workflow’s shared session without checking. Closing this website does not disconnect PowerShell, and a Process-scoped context does not sign you out of your browser or revoke all sign-in sessions.

# Run only when finished with your own dedicated Graph session.
Disconnect-MgGraph

Microsoft references