Public/Invoke-PostureCollection.ps1

# Copyright (c) 2026 Kainor LLC. Source-available, see LICENSE.md.
function Invoke-PostureCollection {
    <#
    .SYNOPSIS
        Collects evidence from the tenant into one run folder with the audit plan's file names (spec 6, Appendix A).
    .DESCRIPTION
        Read-only. The Entra collector (A.1 identity sections): organization and licensing, tenant-wide
        policies, privileged roles active and PIM-eligible, authentication method registration, users, groups,
        app registrations and service principals with credential expiry, Graph application permissions, delegated
        grants, Identity Protection. The Conditional Access snapshot (spec 5.1) is written into the same folder, so
        one folder feeds every domain's checks. Each step logs a failure to errors.txt and the run continues.

        Requires an existing Graph session with Policy.Read.All, Directory.Read.All and Group.Read.All. Optional
        scopes unlock more: User.Read.All and AuditLog.Read.All (sign-in activity, registration report),
        UserAuthenticationMethod.Read.All (registration report), RoleManagement.Read.Directory (PIM),
        OnPremDirectorySynchronization.Read.All (hybrid sync features), IdentityRiskyUser.Read.All and
        IdentityRiskEvent.Read.All (Identity Protection). Missing ones are reported
        with the steps they would unlock. Never connects on its own.
    .PARAMETER OutRoot
        Root folder for evidence. Default: ~/tenantkeep/evidence. The run folder <yyyyMMdd-HHmm> is created under it.
    .PARAMETER OutputFolder
        Write into this exact folder instead.
    .PARAMETER Collector
        Which collectors to run: Entra (A.1 identity sections), Intune (A.1 section 9 and the spec 4.4 additions),
        Exchange (A.2 Exchange Online and the mail DNS records), SharePoint (A.3 tenant settings and sites through
        PnP.PowerShell), Teams (A.3 Teams policies), Defender (effective state through Graph advanced hunting,
        incidents and Secure Score), Purview (A.2 labels, DLP, retention and the rest through Connect-IPPSSession,
        in a process of its own because its cmdlet names overlap Exchange's), Azure (spec 4.13 through Resource Graph
        and Resource Manager reads on a Connect-AzAccount session). Default all eight; a collector whose session is missing is skipped with a warning,
        and refused when it was asked for by name; Defender runs on the Graph session and is skipped with a warning
        when ThreatHunting.Read.All was not granted. See docs/collection.md for the sign-ins.
    .PARAMETER StaleDays
        Threshold for inactive users and devices in the summaries. Default 90.
    .PARAMETER IncludeMembers
        Store group member lists in the Conditional Access snapshot.
    .PARAMETER SkipCaSnapshot
        Do not write the Conditional Access snapshot into the folder.
    .PARAMETER ProfilePath
        profile.json of the tenant. When it carries tenantId, a Graph session in any other tenant is refused before
        anything is read: the guard for a machine that holds sessions to several tenants.
    .PARAMETER SkipPerUserMfa
        Skip the per-user MFA state read (one batched Graph read per member; slow at tens of thousands of users).
    .PARAMETER SkipSiteEnumeration
        Skip Get-PnPTenantSite (30 minutes and more at 20k OneDrives); the ownerless-site check is then not evaluated.
    .PARAMETER SkipMailboxEnumeration
        Skip the Exchange mailbox and CAS mailbox pulls (10 to 20 minutes at 20k mailboxes); the forwarding, shared
        mailbox and per-mailbox protocol checks are then not evaluated.
    .PARAMETER PassThru
        Return a summary object instead of the folder path.
    .EXAMPLE
        Connect-MgGraph -Scopes Policy.Read.All, Directory.Read.All, Group.Read.All, User.Read.All, AuditLog.Read.All, UserAuthenticationMethod.Read.All, RoleManagement.Read.Directory, OnPremDirectorySynchronization.Read.All, IdentityRiskyUser.Read.All, IdentityRiskEvent.Read.All -NoWelcome
        Invoke-PostureCollection

        Writes ~/tenantkeep/evidence/<stamp>/ with the A.1 files and the CA snapshot.
    .EXAMPLE
        Connect-ExchangeOnline -UserPrincipalName reader@contoso.example -ShowBanner:$false
        Invoke-PostureCollection -Collector Exchange -SkipCaSnapshot

        Writes the A.2 exo-* files and dns-01-mail-records into a new run folder. Needs View-Only Organization Management or equivalent.
    .EXAMPLE
        Connect-AzAccount -Tenant <tenant id>
        Invoke-PostureCollection -Collector Azure -SkipCaSnapshot -OutputFolder <the run folder>

        Writes the az-* files (spec 4.13); Reader on the subscriptions or the management group, plus Security Reader.
    .EXAMPLE
        Connect-IPPSSession -UserPrincipalName reader@contoso.example
        Invoke-PostureCollection -Collector Purview -SkipCaSnapshot -OutputFolder <the run folder>

        Writes the A.2 pv-* files into an existing run folder from a process of its own.
    .EXAMPLE
        Connect-PnPOnline -Url https://contoso-admin.sharepoint.com -ClientId <sharePointClientId> -Interactive
        Connect-MicrosoftTeams
        Invoke-PostureCollection -Collector SharePoint, Teams -SkipCaSnapshot

        Writes the A.3 spo-* and teams-* files. The app registration comes from deploy/setup/New-PostureSharePointApp.ps1.
    .EXAMPLE
        Invoke-PostureCollection -OutRoot ./evidence -PassThru | Select-Object Folder, Errors
    .OUTPUTS
        System.String, the run folder. With -PassThru, a summary object.
    .LINK
        docs/m365-environment-audit-plan.md Appendix A
    #>

    [CmdletBinding()]
    [OutputType([string], [pscustomobject])]
    param(
        [ValidateNotNullOrEmpty()] [string] $OutRoot = (Join-Path $HOME 'tenantkeep' 'evidence'),
        [string] $OutputFolder,
        [ValidateSet('Entra', 'Intune', 'Exchange', 'SharePoint', 'Teams', 'Defender', 'Purview', 'Azure')] [string[]] $Collector = @('Entra', 'Intune', 'Exchange', 'SharePoint', 'Teams', 'Defender', 'Purview', 'Azure'),
        [ValidateRange(1, 3650)] [int] $StaleDays = 90,
        [Alias('Profile')] [string] $ProfilePath,
        [switch] $IncludeMembers,
        [switch] $SkipCaSnapshot,
        [switch] $SkipPerUserMfa,
        [switch] $SkipMailboxEnumeration,
        [switch] $SkipSiteEnumeration,
        [switch] $PassThru
    )

    $ErrorActionPreference = 'Stop'
    Set-StrictMode -Version Latest

    $core = @('Policy.Read.All', 'Directory.Read.All', 'Group.Read.All')
    $context = Assert-PostureGraphScope -RequiredScope $core
    if ($ProfilePath) {
        $orgProfile = Import-PostureProfile -Path $ProfilePath
        $expected = [string]$(if ($orgProfile.Contains('tenantId')) { $orgProfile['tenantId'] })
        if ($expected -and $expected -ne [string]$context.TenantId) { throw "The Graph session is in tenant $($context.TenantId), but $ProfilePath belongs to tenant $expected. Sign in to that tenant first, Connect-MgGraph -TenantId $expected, or pass the right profile." }
        # A tenant with nothing in Azure (azure: none in the profile) is never asked for an Azure session; the domain reads as not applicable.
        if (-not $PSBoundParameters.ContainsKey('Collector') -and [string]$(if ($orgProfile.Contains('azure')) { $orgProfile['azure'] }) -eq 'none' -and 'Azure' -in $Collector) {
            $Collector = @($Collector | Where-Object { $_ -ne 'Azure' })
            Write-Verbose 'Profile says azure: none; the Azure collector is skipped.'
        }
    }
    $optional = [ordered]@{
        'User.Read.All'                     = 'Users'
        'OnPremDirectorySynchronization.Read.All' = 'Hybrid sync features'
        'AuditLog.Read.All'                 = 'Users sign-in activity, Auth method registration'
        'UserAuthenticationMethod.Read.All' = 'Auth method registration'
        'RoleManagement.Read.Directory'     = 'PIM eligible assignments, PIM role policies'
        'IdentityRiskyUser.Read.All'        = 'Risky users'
        'IdentityRiskEvent.Read.All'        = 'Risk detections'
        'DeviceManagementManagedDevices.Read.All' = 'Intune managed devices, Autopilot'
        'DeviceManagementConfiguration.Read.All'  = 'Intune compliance and configuration policies, enrollment restrictions, cleanup rule'
        'DeviceManagementServiceConfig.Read.All'  = 'Apple push certificate, MDE connector'
        'DeviceManagementApps.Read.All'           = 'Intune apps, Apple VPP tokens'
        'BitLockerKey.ReadBasic.All'              = 'BitLocker recovery key presence'
        'AttackSimulation.Read.All'               = 'Attack simulation campaigns (skipped quietly when missing)'
        'AccessReview.Read.All'                   = 'Access review definitions'
        'EntitlementManagement.Read.All'          = 'Access packages, catalogs, connected organizations'
        'LifecycleWorkflows.Read.All'             = 'Lifecycle workflows'
        'PrivilegedEligibilitySchedule.Read.AzureADGroup' = 'PIM for Groups'
        'AdministrativeUnit.Read.All'             = 'Administrative units'
        'ThreatHunting.Read.All'                  = 'Defender devices, antivirus state, secure configuration, vulnerabilities (advanced hunting)'
        'SecurityIncident.Read.All'               = 'Defender incidents'
        'SecurityEvents.Read.All'                 = 'Secure Score'
    }
    $granted = @($context.Scopes)
    foreach ($scope in $optional.Keys) {
        if ($scope -notin $granted) { Write-Warning "Scope $scope not granted; expect '$($optional[$scope])' to land in errors.txt." }
    }
    # Session-bound collectors: skipped with a warning by default, refused when named. The module never connects.
    $sessions = [ordered]@{
        Exchange   = @{ test = { Test-PostureExoSession }; hint = 'Connect-ExchangeOnline -UserPrincipalName <reader>' }
        SharePoint = @{ test = { Test-PosturePnpSession }; hint = 'Connect-PnPOnline -Url https://<tenant>-admin.sharepoint.com -ClientId <sharePointClientId from profile.json> -Interactive' }
        Teams      = @{ test = { Test-PostureTeamsSession }; hint = 'Connect-MicrosoftTeams' }
        Purview    = @{ test = { Test-PosturePurviewSession }; hint = 'Connect-IPPSSession -UserPrincipalName <reader>' }
        Azure      = @{ test = { Test-PostureAzureSession }; hint = 'Connect-AzAccount -Tenant <tenant id>' }
    }
    $run = @{}
    $run['Defender'] = $Collector -contains 'Defender'
    if ($run['Defender'] -and 'ThreatHunting.Read.All' -notin $granted) {
        if ($PSBoundParameters.ContainsKey('Collector')) { throw 'The Defender collector needs ThreatHunting.Read.All on the Graph session (plus SecurityIncident.Read.All and SecurityEvents.Read.All for incidents and Secure Score).' }
        Write-Warning 'ThreatHunting.Read.All not granted; skipping the Defender collector. Add it to Connect-MgGraph -Scopes, or name the collectors you want in -Collector to silence this.'
        $run['Defender'] = $false
    }
    foreach ($name in $sessions.Keys) {
        $run[$name] = $Collector -contains $name
        if ($run[$name] -and -not (& $sessions[$name].test)) {
            if ($PSBoundParameters.ContainsKey('Collector')) { throw "The $name collector needs an open session: $($sessions[$name].hint) first. The module never connects on its own." }
            Write-Warning "No $name session; skipping the $name collector. Run $($sessions[$name].hint) first, or name the collectors you want in -Collector to silence this."
            $run[$name] = $false
        }
    }

    $startedUtc = [datetime]::UtcNow
    $folder = if ($OutputFolder) {
        New-Item -ItemType Directory -Path $OutputFolder -Force | Out-Null
        (Resolve-Path -LiteralPath $OutputFolder).Path
    }
    else { New-PostureEvidenceFolder -OutRoot $OutRoot }
    $script:GraphApiVersionsUsed.Clear()

    try {
        $files = [System.Collections.Generic.List[string]]::new()
        $ran = [System.Collections.Generic.List[string]]::new()

        if (-not $SkipCaSnapshot) {
            $snap = Export-PostureCaSnapshot -OutputFolder $folder -IncludeMembers:$IncludeMembers -PassThru
            foreach ($f in $snap.Files) { $files.Add($f) }
            $ran.Add('ConditionalAccess')
        }
        if ($Collector -contains 'Entra') {
            $r = Invoke-PostureEntraCollection -Folder $folder -StaleDays $StaleDays -AsOf $startedUtc -SkipPerUserMfa:$SkipPerUserMfa
            foreach ($f in $r.files) { $files.Add($f) }
            $ran.Add('Entra')
        }
        if ($Collector -contains 'Intune') {
            $r = Invoke-PostureIntuneCollection -Folder $folder -StaleDays $StaleDays -AsOf $startedUtc
            foreach ($f in $r.files) { $files.Add($f) }
            $ran.Add('Intune')
        }
        if ($run.Exchange) {
            $r = Invoke-PostureExchangeCollection -Folder $folder -SkipMailboxEnumeration:$SkipMailboxEnumeration
            foreach ($f in $r.files) { $files.Add($f) }
            $ran.Add('Exchange')
        }
        if ($run.SharePoint) {
            $r = Invoke-PostureSharePointCollection -Folder $folder -SkipSiteEnumeration:$SkipSiteEnumeration
            foreach ($f in $r.files) { $files.Add($f) }
            $ran.Add('SharePoint')
        }
        if ($run.Teams) {
            $r = Invoke-PostureTeamsCollection -Folder $folder
            foreach ($f in $r.files) { $files.Add($f) }
            $ran.Add('Teams')
        }
        if ($run.Purview) {
            $r = Invoke-PosturePurviewCollection -Folder $folder
            foreach ($f in $r.files) { $files.Add($f) }
            $ran.Add('Purview')
        }
        if ($run.Azure) {
            $r = Invoke-PostureAzureCollection -Folder $folder
            foreach ($f in $r.files) { $files.Add($f) }
            $ran.Add('Azure')
        }
        if ($run.Defender) {
            $r = Invoke-PostureDefenderCollection -Folder $folder -AsOf $startedUtc
            foreach ($f in $r.files) { $files.Add($f) }
            $ran.Add('Defender')
        }

        $errorsPath = Join-Path $folder 'errors.txt'
        $errors = @(if (Test-Path -LiteralPath $errorsPath) { Get-Content -LiteralPath $errorsPath })   # @( ) outside the if: an empty array inside it unrolls to null
        # Collectors may run in separate processes into one folder (the Exchange, PnP and Teams modules do not share a
        # process on macOS); a manifest already there keeps its collectors and start time.
        $previous = $null
        $manifestPath = Join-Path $folder 'collection.json'
        if ($OutputFolder -and (Test-Path -LiteralPath $manifestPath)) { try { $previous = Get-Content -Raw -LiteralPath $manifestPath | ConvertFrom-Json -AsHashtable -Depth 10 } catch { $previous = $null } }
        $allCollectors = @(@($(if ($previous) { $previous['collectors'] })) + $ran.ToArray() | Where-Object { $_ } | Select-Object -Unique)
        # Module versions: what this process loaded, over what an earlier process into the same folder recorded.
        $modules = [ordered]@{}
        if ($previous -and $previous['modules']) { foreach ($k in @($previous['modules'].Keys)) { $modules[$k] = $previous['modules'][$k] } }
        $used = Get-PostureModuleVersionUsed
        foreach ($k in @($used.Keys)) { if ($used[$k] -or -not $modules.Contains($k)) { $modules[$k] = $used[$k] } }
        $manifest = [ordered]@{
            product          = 'TenantKeep.Posture'
            moduleVersion    = $script:ModuleVersion
            collectors       = $allCollectors
            tenantId         = $context.TenantId
            account          = $context.Account
            authType         = $context.AuthType
            scopes           = @($granted | Sort-Object)
            timestampUtc     = $(if ($previous -and $previous['timestampUtc']) { (ConvertTo-PostureUtcDateTime $previous['timestampUtc']).ToString('o') } else { $startedUtc.ToString('o') })   # ConvertFrom-Json turned it into a DateTime
            completedUtc     = [datetime]::UtcNow.ToString('o')
            graphApiVersions = @($script:GraphApiVersionsUsed | Sort-Object)
            modules          = $modules
            powerShell       = $PSVersionTable.PSVersion.ToString()
            os               = [System.Runtime.InteropServices.RuntimeInformation]::OSDescription
            staleDays        = $StaleDays
            files            = @(Get-ChildItem -LiteralPath $folder -File | Where-Object { $_.Name -notin @('transcript.txt', 'errors.txt') } | ForEach-Object { $_.Name } | Sort-Object)
            errorCount       = $errors.Count
            errors           = $errors
        }
        $files.Add((Write-PostureEvidence -Folder $folder -Name 'collection' -InputObject $manifest))
        if ($errors.Count -gt 0) { Write-Warning "$($errors.Count) step(s) failed; see $errorsPath" }

        if ($PassThru) {
            return [pscustomobject]@{ Folder = $folder; Collectors = $allCollectors; Files = $files.ToArray(); Errors = $errors; Manifest = $manifest }
        }
        return $folder
    }
    finally {
        if (-not $OutputFolder) { try { Stop-Transcript | Out-Null } catch { Write-Verbose 'No transcript to stop.' } }
    }
}