Public/Connect-NSPM365Exchange.ps1

function Connect-NSPM365Exchange {
    <#
    .SYNOPSIS
        Selects a tenant-verified Exchange REST connection, optionally connecting interactively.
    .DESCRIPTION
        Validation only unless Connect is explicit. Reuses a uniquely selected connection without
        disconnecting anything. New connections use a unique command prefix and import only the
        investigation read commands. Requires installed ExchangeOnlineManagement. Never installs,
        restores a cache, changes tenant settings or obtains credentials from a secret store.
        DelegatedOrganization is an explicit customer domain for an existing partner access path.
    .EXAMPLE
        Connect-NSPM365Exchange -TenantId '00000000-0000-4000-8000-000000000001' -Connect -UserPrincipalName admin@contoso.com -DisableWAM
    .EXAMPLE
        Connect-NSPM365Exchange -TenantId '00000000-0000-4000-8000-000000000001' -ConnectionId $connectionId
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][guid]$TenantId,
        [switch]$Connect,
        [string]$ConnectionId,
        [string]$UserPrincipalName,
        [ValidatePattern('^[A-Za-z][A-Za-z0-9]{0,15}$')][string]$Prefix = 'IR',
        [ValidatePattern('^[A-Za-z0-9][A-Za-z0-9.-]+\.[A-Za-z]{2,}$')][string]$DelegatedOrganization,
        [switch]$DisableWAM,
        [switch]$UseDeviceCode
    )
    if ($TenantId -eq [guid]::Empty) { throw 'TenantId cannot be empty.' }
    if ($UseDeviceCode -and ($PSVersionTable.PSVersion -lt [version]'7.0.3' -or $DisableWAM -or $UserPrincipalName)) {
        throw 'Exchange device flow requires PowerShell 7.0.3+, without DisableWAM or UserPrincipalName.'
    }
    if ($Prefix -eq 'EXO') { throw 'EXO is a reserved command prefix.' }
    Import-NSPInvestigationDependency -Name ExchangeOnlineManagement -MinimumVersion '3.0.0'
    $all = @(Get-ConnectionInformation -ErrorAction Stop)
    $matching = @($all | Where-Object { $_.State -eq 'Connected' -and -not $_.IsEopSession -and [string]$_.TenantID -eq $TenantId.ToString() })
    if ($ConnectionId -or $matching.Count) {
        return Get-NSPInvestigationExchangeConnection -TenantId $TenantId -ConnectionId $ConnectionId
    }
    if (-not $Connect) { throw 'No matching Exchange connection. Use Connect explicitly to authenticate.' }
    if (-not $UseDeviceCode -and -not $UserPrincipalName) { throw 'Specify the approved operator UserPrincipalName or UseDeviceCode.' }
    if (@($all | Where-Object { [string]$_.ModulePrefix -eq $Prefix }).Count) { throw 'Requested Exchange prefix is already in use.' }
    $connectArgs = @{ Prefix = $Prefix; ShowBanner = $false; ErrorAction = 'Stop'; CommandName = @(
        'Get-Mailbox', 'Get-InboxRule', 'Get-AcceptedDomain', 'Get-MailboxPermission',
        'Get-RecipientPermission', 'Get-MessageTraceV2', 'Get-MessageTraceDetailV2'
    ) }
    if ($UserPrincipalName) { $connectArgs.UserPrincipalName = $UserPrincipalName }
    if ($DelegatedOrganization) { $connectArgs.DelegatedOrganization = $DelegatedOrganization }
    if ($UseDeviceCode) { $connectArgs.Device = $true }
    if ($DisableWAM) { $connectArgs.DisableWAM = $true }
    $native = Get-Command Connect-ExchangeOnline -ErrorAction Stop
    foreach ($key in $connectArgs.Keys) {
        if (-not $native.Parameters.ContainsKey($key)) { throw "Installed Exchange connector does not support $key. No upgrade was attempted." }
    }
    $before = @($all | ForEach-Object { [string]$_.ConnectionId })
    & $native @connectArgs | Out-Null
    $created = @(Get-ConnectionInformation -ErrorAction Stop | Where-Object {
        [string]$_.ConnectionId -notin $before -and $_.State -eq 'Connected' -and [string]$_.ModulePrefix -eq $Prefix
    })
    if ($created.Count -ne 1 -or [string]$created[0].TenantID -ne $TenantId.ToString()) {
        throw 'New Exchange connection did not match the requested tenant uniquely. No evidence was read; connections were left intact for operator review.'
    }
    Get-NSPInvestigationExchangeConnection -TenantId $TenantId -ConnectionId ([string]$created[0].ConnectionId)
}