Public/Export-NSPM365EntraActivity.ps1
|
function Export-NSPM365EntraActivity { <# .SYNOPSIS Preserves scoped user sign-ins and directory changes through an existing Graph connection. .DESCRIPTION Requires an explicitly selected tenant GUID, account and time window [StartTime, EndTime). Never authenticates, installs dependencies, retrieves message bodies or performs containment. Use an approved existing Graph context with AuditLog.Read.All and User.Read.All (or Directory.Read.All). Delegated roles, licensing and log retention also affect availability. Interactive and non-interactive user sign-ins use beta with explicit event-type filters. Directory audits include actions initiated by the user and changes targeting the user. Raw pages and SHA-256 are preserved; any failed stream makes Complete false, even when other streams succeed. OutputPath must be new or empty and kept outside version control. Only the global Microsoft Graph cloud is supported. No service-principal sign-ins or tenant-wide app hunts are implied by this account-scoped command. .EXAMPLE Export-NSPM365EntraActivity -TenantId $tenantGuid -UserPrincipalName $upn -StartTime '2026-10-27T14:30:00Z' -EndTime ([datetimeoffset]::UtcNow) -OutputPath $newEvidenceFolder #> [CmdletBinding()] param( [Parameter(Mandatory)][guid]$TenantId, [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$UserPrincipalName, [Parameter(Mandatory)][datetimeoffset]$StartTime, [Parameter(Mandatory)][datetimeoffset]$EndTime, [Parameter(Mandatory)][string]$OutputPath, [ValidateRange(1, 10000)][int]$MaxPages = 1000 ) $ErrorActionPreference = 'Stop' if ($StartTime -ge $EndTime) { throw 'StartTime must precede EndTime.' } Write-NSPInvestigationProgress -Activity 'Entra' -Status 'Checking current tenant and resolving the requested account.' Assert-NSPInvestigationTenant -TenantId $TenantId $userUri = 'users/' + [uri]::EscapeDataString($UserPrincipalName) + '?$select=id,userPrincipalName,accountEnabled' $user = Invoke-NSPGraphRetry { Invoke-NSPGraphRequest -Uri $userUri } -Activity 'Entra account lookup' $userId = [guid]::Empty if (-not [guid]::TryParse([string]$user.id, [ref]$userId) -or [string]$user.userPrincipalName -ne $UserPrincipalName) { throw 'Resolved user does not match the requested account.' } $OutputPath = New-NSPInvestigationOutput -Path $OutputPath $snapshot = Join-Path $OutputPath 'User.json' Save-NSPInvestigationJson -Path $snapshot -Data $user $start = $StartTime.UtcDateTime.ToString('o') $end = $EndTime.UtcDateTime.ToString('o') $manifest = [ordered]@{ SchemaVersion=1; Status='InProgress'; TenantId=$TenantId.ToString(); UserPrincipalName=$UserPrincipalName UserId=$userId.ToString(); StartUtc=$start; EndUtcExclusive=$end; StartedUtc=[datetime]::UtcNow.ToString('o') UserSnapshotSha256=(Get-FileHash -LiteralPath $snapshot -Algorithm SHA256).Hash ModuleVersion=(Get-Module NSP.M365.Investigation).Version.ToString() Coverage='Account-scoped available logs only. Empty results do not prove absence; licensing, retention and permissions may limit data.' Streams=@() } $manifestPath = Join-Path $OutputPath 'CollectionManifest.json' Save-NSPInvestigationJson -Path $manifestPath -Data $manifest $streams = @( @{ Name='InteractiveSignIns'; ApiVersion='beta'; Base='auditLogs/signIns'; Filter="userId eq '$userId' and createdDateTime ge $start and createdDateTime lt $end and signInEventTypes/any(t:t eq 'interactiveUser')" }, @{ Name='NonInteractiveSignIns'; ApiVersion='beta'; Base='auditLogs/signIns'; Filter="userId eq '$userId' and createdDateTime ge $start and createdDateTime lt $end and signInEventTypes/any(t:t eq 'nonInteractiveUser')" }, @{ Name='DirectoryActions'; ApiVersion='v1.0'; Base='auditLogs/directoryAudits'; Filter="activityDateTime ge $start and activityDateTime lt $end and initiatedBy/user/id eq '$userId'" }, @{ Name='DirectoryChanges'; ApiVersion='v1.0'; Base='auditLogs/directoryAudits'; Filter="activityDateTime ge $start and activityDateTime lt $end and targetResources/any(t:t/id eq '$userId')" } ) $streamIndex = 0 foreach ($stream in $streams) { $streamIndex++ Write-NSPInvestigationProgress -Activity 'Entra' -Status ("Stream {0}/{1}: {2}" -f $streamIndex, $streams.Count, $stream.Name) $uri = New-NSPHuntFilterUri -Base $stream.Base -Filter $stream.Filter $result = Export-NSPInvestigationCollection -Uri $uri -ApiVersion $stream.ApiVersion -OutputPath $OutputPath -Name $stream.Name -MaxPages $MaxPages $manifest.Streams += $result | Select-Object Name, Complete, Error, NextLink, Count, Pages Save-NSPInvestigationJson -Path $manifestPath -Data $manifest } $complete = @($manifest.Streams | Where-Object { -not $_.Complete }).Count -eq 0 $manifest.Status = if ($complete) { 'Completed' } else { 'Partial' } $manifest.CompletedUtc = [datetime]::UtcNow.ToString('o') Save-NSPInvestigationJson -Path $manifestPath -Data $manifest if (-not $complete) { Write-Warning 'Some Entra streams are incomplete. Inspect CollectionManifest.json; do not interpret failures as zero activity.' } [pscustomobject]@{ Complete=$complete; OutputPath=$OutputPath; Manifest=$manifestPath; Streams=$manifest.Streams } } |