Public/Connect-NSPM365Investigation.ps1

function Connect-NSPM365Investigation {
    <#
    .SYNOPSIS
        Composes existing Graph authentication and tenant-safe Exchange setup for investigation.
    .DESCRIPTION
        Validation only by default; Connect explicitly enables delegated interactive login.
        Requires existing approved permissions and installed dependencies. Stop at an unexpected
        consent prompt; this command does not create registrations, grant access or install modules.
        Graph has one process context. A different existing tenant is rejected without replacing it.
        Phase lets unavailable permissions/services remain independent. No evidence is collected.
    .EXAMPLE
        Connect-NSPM365Investigation -TenantId $tenant -Connect -Phase Exchange -UserPrincipalName admin@contoso.com -DisableWAM
    .EXAMPLE
        Connect-NSPM365Investigation -TenantId $tenant -Connect -Phase Graph -ClientId $approvedClient -UseDeviceCode
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][guid]$TenantId,
        [switch]$Connect,
        [ValidateSet('All','Graph','Exchange')][string]$Phase = 'All',
        [string]$ClientId,
        [switch]$UseDeviceCode,
        [switch]$IncludeAuthenticationMethods,
        [string]$UserPrincipalName,
        [string]$ExchangeConnectionId,
        [ValidatePattern('^[A-Za-z][A-Za-z0-9]{0,15}$')][string]$ExchangePrefix = 'IR',
        [string]$DelegatedOrganization,
        [switch]$DisableWAM
    )
    if ($TenantId -eq [guid]::Empty) { throw 'TenantId cannot be empty.' }
    if ($UseDeviceCode -and $Phase -ne 'Graph' -and ($PSVersionTable.PSVersion -lt [version]'7.0.3' -or $DisableWAM -or $UserPrincipalName)) {
        throw 'For Exchange device flow use PowerShell 7.0.3+ without DisableWAM/UserPrincipalName, or connect the phases separately.'
    }
    $prior = $env:NSP_NO_AUTOINSTALL
    try {
        $env:NSP_NO_AUTOINSTALL = '1'
        # Preflight both dependencies before interactive authentication.
        if ($Phase -in 'All','Exchange') { Import-NSPInvestigationDependency -Name ExchangeOnlineManagement -MinimumVersion '3.0.0' }
        if ($Phase -in 'All','Graph') {
            Import-NSPInvestigationDependency -Name Microsoft.Graph.Authentication
            Import-NSPM365Graph
            $context = Get-MgContext
            if ($context -and [string]$context.TenantId -ne $TenantId.ToString()) { throw 'Existing Graph context belongs to a different tenant. Use a separate process.' }
            if ($context -and $context.AuthType -and $context.AuthType -ne 'Delegated') { throw 'Existing Graph context is not delegated. Use the existing app-only collection path or a separate process.' }
            if ($context -and $ClientId -and [string]$context.ClientId -ne $ClientId) { throw 'Existing Graph context belongs to a different application. Use a separate process.' }
            $scopes = @('AuditLog.Read.All','Directory.Read.All','Mail.Read.Shared','AuditLogsQuery.Read.All')
            if ($IncludeAuthenticationMethods) { $scopes += 'UserAuthenticationMethod.Read.All' }
            $graphArgs = @{ Scopes = $scopes; TenantId = $TenantId.ToString(); Connect = [bool]$Connect }
            if ($ClientId) { $graphArgs.ClientId = $ClientId }
            if ($UseDeviceCode) { $graphArgs.UseDeviceCode = $true }
            $graph = Connect-NSPGraph @graphArgs
            if (-not $graph -or [string]$graph.TenantId -ne $TenantId.ToString()) { throw 'Graph authentication returned a different tenant.' }
            if ($graph.AuthType -and $graph.AuthType -ne 'Delegated') { throw 'This setup helper requires an approved delegated Graph context. Existing app-only collection remains separate.' }
        }
        $exchange = $null
        if ($Phase -in 'All','Exchange') {
            $exchangeArgs = @{ TenantId = $TenantId; Connect = [bool]$Connect; Prefix = $ExchangePrefix }
            if ($ExchangeConnectionId) { $exchangeArgs.ConnectionId = $ExchangeConnectionId }
            if ($UserPrincipalName) { $exchangeArgs.UserPrincipalName = $UserPrincipalName }
            if ($DelegatedOrganization) { $exchangeArgs.DelegatedOrganization = $DelegatedOrganization }
            if ($DisableWAM) { $exchangeArgs.DisableWAM = $true }
            if ($UseDeviceCode) { $exchangeArgs.UseDeviceCode = $true }
            $exchange = Connect-NSPM365Exchange @exchangeArgs
        }
        [pscustomobject]@{ TenantId = $TenantId.ToString(); Phase = $Phase; GraphReady = ($Phase -in 'All','Graph');
            ExchangeReady = [bool]$exchange; ExchangeConnectionId = $(if ($exchange) { [string]$exchange.ConnectionId });
            ExchangePrefix = $(if ($exchange) { [string]$exchange.ModulePrefix }); EvidenceCollected = $false }
    } finally { $env:NSP_NO_AUTOINSTALL = $prior }
}