Public/Invoke-NSPM365AuditSearch.ps1

function Invoke-NSPM365AuditSearch {
    <#
    .SYNOPSIS
        Prepares, submits or resumes a scoped Purview audit search without automatic authentication.
    .DESCRIPTION
        The default prepares criteria locally only. -Submit explicitly creates one search;
        -QueryName or -QueryId attaches to an existing job without submitting another. -Resume
        uses SearchState.json in the same OutputPath; it never submits a job, even after a failed
        or uncertain submission. On an uncertain POST, attach by name/ID in a fresh directory.
        Live actions require an approved existing Graph connection to the explicit tenant and
        appropriate AuditLogsQuery permissions/roles. No installation or consent is attempted.
        Query user filters must exactly match the approved address list: the account UPNs plus
        any -AdditionalUserId values and -ResolveMailAddress results. Mailbox audit records can be
        logged under the primary SMTP address instead of the UPN, so a UPN-only search warns and
        saves AddressCoverage = UpnOnly. -ResolveMailAddress reads mail and proxyAddresses for each
        account through the existing connection (User.Read.All or Directory.Read.All) before a
        search is submitted or attached; if that read fails, nothing is submitted. Attach captures actual
        UTC bounds rather than inferring them from the name. Operations/workloads are not
        restricted on new searches. -Export only retrieves records after status succeeded.
        Each export attempt uses a fresh directory with preserved JSON pages, hashes and a CSV
        compatible with audit triage. Failed pages make export Partial, never Completed.
        Status polling is bounded; default is one status check. Only global Graph is supported.
        Evidence and SearchState.json contain identifiers: keep OutputPath outside version control.
    .EXAMPLE
        Invoke-NSPM365AuditSearch -TenantId $tenantGuid -UserPrincipalName $upn -QueryName $existingSearchName -OutputPath $newSearchFolder -Export
    .EXAMPLE
        Invoke-NSPM365AuditSearch -TenantId $tenantGuid -UserPrincipalName $upn -StartTime '2026-10-27T14:30:00Z' -EndTime ([datetimeoffset]::UtcNow) -SearchName 'Account audit' -OutputPath $newPlanFolder
    .EXAMPLE
        Invoke-NSPM365AuditSearch -TenantId $tenantGuid -UserPrincipalName $upn -OutputPath $existingSearchFolder -Resume -Export
    #>

    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName='Prepare')]
    param(
        [Parameter(Mandatory)][guid]$TenantId,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string[]]$UserPrincipalName,
        [Parameter(Mandatory, ParameterSetName='Prepare')]
        [Parameter(Mandatory, ParameterSetName='Submit')][datetimeoffset]$StartTime,
        [Parameter(Mandatory, ParameterSetName='Prepare')]
        [Parameter(Mandatory, ParameterSetName='Submit')][datetimeoffset]$EndTime,
        [Parameter(Mandatory, ParameterSetName='Prepare')]
        [Parameter(Mandatory, ParameterSetName='Submit')][string]$SearchName,
        [Parameter(Mandatory, ParameterSetName='Submit')][switch]$Submit,
        [Parameter(Mandatory, ParameterSetName='Name')][ValidateNotNullOrEmpty()][string]$QueryName,
        [Parameter(Mandatory, ParameterSetName='Id')][guid]$QueryId,
        [Parameter(Mandatory, ParameterSetName='Resume')][switch]$Resume,
        [Parameter(Mandatory)][string]$OutputPath,
        [switch]$Export,
        [string[]]$AdditionalUserId=@(),
        [Parameter(ParameterSetName='Submit')][Parameter(ParameterSetName='Name')][Parameter(ParameterSetName='Id')][switch]$ResolveMailAddress,
        [ValidateRange(0, 3600)][int]$WaitTimeoutSeconds=0,
        [ValidateRange(1, 60)][int]$PollIntervalSeconds=10,
        [ValidateRange(1, 10000)][int]$MaxPages=1000
    )
    $ErrorActionPreference = 'Stop'
    $users = @($UserPrincipalName | ForEach-Object { $_.Trim().ToLowerInvariant() } | Sort-Object -Unique)
    if (-not $users.Count -or @($users | Where-Object { -not $_ -or $_ -notlike '*@*' }).Count) { throw 'Specify nonempty account UPNs.' }
    $extra = @($AdditionalUserId | ForEach-Object { ([string]$_).Trim().ToLowerInvariant() } | Where-Object { $_ } | Sort-Object -Unique)
    if (@($extra | Where-Object { $_ -notlike '*@*' }).Count) { throw 'AdditionalUserId values must be addresses.' }
    $filterUsers = @(@($users) + @($extra) | Sort-Object -Unique)
    $statePath = Join-Path $OutputPath 'SearchState.json'
    if ($Resume) {
        $state = Get-Content -LiteralPath $statePath -Raw -ErrorAction Stop | ConvertFrom-Json
        if ($state.TenantId -ne $TenantId.ToString() -or @(Compare-Object @($state.Users) $users).Count) { throw 'Saved search tenant/accounts do not match the requested scope.' }
        if (-not $state.QueryId) { throw 'No saved query ID. Resume never submits. Attach to the existing job by name/ID in a new directory.' }
        $null = [guid]::Parse([string]$state.QueryId)
        # State files written before address coverage existed were UPN-only searches.
        foreach ($name in 'FilterUsers','AddressCoverage') {
            if (-not $state.PSObject.Properties[$name]) { Add-Member -InputObject $state -NotePropertyName $name -NotePropertyValue $null }
        }
        if (-not $state.FilterUsers) { $state.FilterUsers = $users; $state.AddressCoverage = 'UpnOnly' }
        $saved = @($state.FilterUsers | ForEach-Object { ([string]$_).ToLowerInvariant() } | Sort-Object -Unique)
        if ($PSBoundParameters.ContainsKey('AdditionalUserId') -and @(Compare-Object $saved $filterUsers).Count) { throw 'Saved search address filters do not match the requested scope.' }
        $filterUsers = $saved
        $OutputPath = (Resolve-Path -LiteralPath $OutputPath).ProviderPath
    } else {
        if ($PSCmdlet.ParameterSetName -in 'Prepare','Submit' -and $StartTime -ge $EndTime) { throw 'StartTime must precede EndTime.' }
        $OutputPath = New-NSPInvestigationOutput -Path $OutputPath
        $statePath = Join-Path $OutputPath 'SearchState.json'
        $state = [pscustomobject]@{ SchemaVersion=1; ModuleVersion=(Get-Module NSP.M365.Investigation).Version.ToString(); TenantId=$TenantId.ToString(); Users=$users; FilterUsers=$filterUsers; AddressCoverage=$(if ($extra.Count) { 'OperatorSupplied' } else { 'UpnOnly' }); QueryId=$null; Status='Prepared'; Query=$null; ExportStatus='NotRequested'; ExportPath=$null; UpdatedUtc=[datetime]::UtcNow.ToString('o') }
        if ($PSCmdlet.ParameterSetName -in 'Prepare','Submit') {
            $state.Query = @{ displayName=$SearchName; filterStartDateTime=$StartTime.UtcDateTime.ToString('o'); filterEndDateTime=$EndTime.UtcDateTime.ToString('o'); userPrincipalNameFilters=$filterUsers }
        }
        Save-NSPInvestigationJson -Path $statePath -Data $state
    }
    if ($PSCmdlet.ParameterSetName -eq 'Prepare' -or ($Submit -and -not $PSCmdlet.ShouldProcess($TenantId.ToString(), 'Submit scoped Purview audit search'))) { return $state }
    Assert-NSPInvestigationTenant -TenantId $TenantId
    if ($ResolveMailAddress) {
        # A failed lookup throws here, before any search is submitted or selected.
        $resolved = @(foreach ($account in $users) { Get-NSPInvestigationMailAddress -UserPrincipalName $account })
        $filterUsers = @(@($filterUsers) + @($resolved) | Sort-Object -Unique)
        $state.FilterUsers = $filterUsers
        $state.AddressCoverage = 'Resolved'
        if ($Submit) { $state.Query.userPrincipalNameFilters = $filterUsers }
        Save-NSPInvestigationJson -Path $statePath -Data $state
    } elseif ($state.AddressCoverage -eq 'UpnOnly') {
        Write-Warning 'This search is filtered by UPN only. Mailbox records logged under a different primary SMTP or alias address may be missing. For a new search use -ResolveMailAddress or -AdditionalUserId.'
    }
    $base = 'security/auditLog/queries'
    if ($Submit) {
        $state.Status = 'SubmissionPending'
        Save-NSPInvestigationJson -Path $statePath -Data $state
        try {
            # No retry around POST: a lost response must not cause a duplicate search.
            $query = Invoke-NSPGraphRequest -Method POST -Uri $base -Body $state.Query
            $null = [guid]::Parse([string]$query.id)
            $state.QueryId = [string]$query.id
        } catch {
            $state.Status = 'SubmissionUncertain'
            Save-NSPInvestigationJson -Path $statePath -Data $state
            throw
        }
        # Persist the ID before the next network call.
        $state.Status = 'Submitted'
        Save-NSPInvestigationJson -Path $statePath -Data $state
    } elseif ($PSCmdlet.ParameterSetName -eq 'Name') {
        $filter = "displayName eq '$($QueryName.Replace("'", "''"))'"
        $listing = Export-NSPInvestigationCollection -Uri (New-NSPHuntFilterUri -Base $base -Filter $filter) -OutputPath $OutputPath -Name 'QueryLookup' -MaxPages $MaxPages
        if (-not $listing.Complete) { throw 'Query lookup incomplete; no job was selected.' }
        $named = @($listing.Items | Where-Object { [string]$_.displayName -ceq $QueryName })
        if ($named.Count -ne 1) { throw 'Expected exactly one query with that exact name. Use QueryId to disambiguate; no search was submitted.' }
        $null = [guid]::Parse([string]$named[0].id)
        $state.QueryId = [string]$named[0].id
    } elseif ($PSCmdlet.ParameterSetName -eq 'Id') { $state.QueryId = $QueryId.ToString() }
    Save-NSPInvestigationJson -Path $statePath -Data $state
    $timer = [Diagnostics.Stopwatch]::StartNew()
    do {
        $uri = "$base/$($state.QueryId)"
        $query = Invoke-NSPGraphRetry { Invoke-NSPGraphRequest -Uri $uri }
        if ([string]$query.id -ne $state.QueryId) { throw 'Query response ID does not match the requested job.' }
        $actualUsers = @($query.userPrincipalNameFilters | ForEach-Object { ([string]$_).ToLowerInvariant() } | Sort-Object -Unique)
        if (-not $actualUsers.Count -or @(Compare-Object $actualUsers $filterUsers).Count) { throw 'Query account filters do not match the approved account list. No records exported.' }
        $state.Query = $query
        $state.Status = [string]$query.status
        $state.UpdatedUtc = [datetime]::UtcNow.ToString('o')
        Save-NSPInvestigationJson -Path $statePath -Data $state
        if ($state.Status -notin 'notStarted','running' -or $timer.Elapsed.TotalSeconds -ge $WaitTimeoutSeconds) { break }
        $remaining = [math]::Max(1, [math]::Ceiling($WaitTimeoutSeconds - $timer.Elapsed.TotalSeconds))
        Start-Sleep -Seconds ([math]::Min($PollIntervalSeconds, $remaining))
    } while ($true)
    if ($Export -and $state.Status -eq 'succeeded' -and $state.ExportStatus -ne 'Completed') {
        $exportPath = New-NSPInvestigationOutput -Path (Join-Path $OutputPath ('Export-' + [guid]::NewGuid().ToString('N')))
        $state.ExportStatus = 'InProgress'
        $state.ExportPath = $exportPath
        Save-NSPInvestigationJson -Path $statePath -Data $state
        $result = Export-NSPInvestigationCollection -Uri "$base/$($state.QueryId)/records" -OutputPath $exportPath -Name 'AuditRecords' -MaxPages $MaxPages
        $csv = Join-Path $exportPath 'Audit.csv'
        $normalized = @(foreach ($record in $result.Items) {
            [pscustomobject]@{
                # Always UTC with a zone marker: a bare [string] cast differs between 5.1 and 7.
                RecordId=[string]$record.id; CreationDate=$(try { (ConvertTo-NSPHuntUtc $record.createdDateTime).ToString('o') } catch { [string]$record.createdDateTime })
                RecordType=[string]$record.auditLogRecordType; Operation=[string]$record.operation
                UserId=[string]$record.userPrincipalName
                AuditData=if ($record.auditData -is [string]) { $record.auditData } else { ConvertTo-Json -InputObject $record.auditData -Depth 100 -Compress }
            }
        })
        if ($normalized.Count) { $normalized | Export-Csv -LiteralPath $csv -NoTypeInformation -Encoding UTF8 }
        else { [IO.File]::WriteAllText($csv, '"RecordId","CreationDate","RecordType","Operation","UserId","AuditData"' + "`r`n", (New-Object Text.UTF8Encoding $false)) }
        $state.ExportStatus = if ($result.Complete) { 'Completed' } else { 'Partial' }
        Save-NSPInvestigationJson -Path (Join-Path $exportPath 'ExportManifest.json') -Data @{
            TenantId=$state.TenantId; QueryId=$state.QueryId; Query=$state.Query; Status=$state.ExportStatus
            FilterUsers=$filterUsers; AddressCoverage=$state.AddressCoverage
            Count=$result.Count; Pages=$result.Pages; Error=$result.Error; NextLink=$result.NextLink
            CsvFile='Audit.csv'; CsvSha256=(Get-FileHash -LiteralPath $csv -Algorithm SHA256).Hash
            CompletedUtc=[datetime]::UtcNow.ToString('o')
        }
        Save-NSPInvestigationJson -Path $statePath -Data $state
        if (-not $result.Complete) { Write-Warning 'Audit export is partial. Preserve this attempt; Resume -Export starts a fresh attempt without submitting another job.' }
    }
    $state
}