-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path45-Search-MailboxMessage.ps1
More file actions
883 lines (807 loc) · 47.4 KB
/
Copy path45-Search-MailboxMessage.ps1
File metadata and controls
883 lines (807 loc) · 47.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
# Bitpusher
# \`._,'/
# (_- -_)
# \o/
# The Digital
# Fox
# @VinceVulpes
# https://theTechRelay.com
# https://github.com/bitpusher2k
#
# Search-MailboxMessage.ps1 - By Bitpusher/The Digital Fox
# v5.0.2 - DEF CON edition - last updated 2026-08-05
#
# Script to search Exchange Online mailbox(s) using Graph API by Message IDs, subject, sender, date.
# Retrieval in this manner is faster than eDiscovery/content searches.
# Use on a mailbox restored from backup for searches that include messages which have been deleted by threat actor.
# Saves found messages to folder along with a CSV formatted index of message metadata.
#
# Script can create the needed Enterprise App Registration with Mail.Read scope, or
# pass -TenantID, -ClientID, and -ClientSecret parameters to use an already created app.
# Creating/renewing the app requires an MgGraph connection with Application.ReadWrite.All & User.Read.All scopes,
# and creates a secret that expires -SecretValidityDays (default 10) days from creation. The secret is REUSED on
# later runs until it nears expiry - runs that have a saved, non-expired secret need no provisioning permissions.
# Connection information from a previously created application by this script will be in MailAppInfo.json.
#
# https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/RegisteredApps
#
#
# Retrieving all InternetMessageId's from "AuditData" blocks in a UAL log export:
# $Ual = Import-CSV .\UALexport.csv
# $UalJson = $Ual.auditdata
# $UalJson = $UalJson | ConvertFrom-Json
# $InternetMessageId = $UalJson.folders.folderitems.internetmessageid
# $InternetMessageId | Out-File .\QueryList.txt -Encoding Utf8NoBom
#
# Be sure to include the full Message ID string (which may include angle brackets) and enclose the value in quotation marks (for example, "d9683b4c-127b-413a-ae2e-fa7dfb32c69d@DM3NAM06BG401.Eop-nam06.prod.protection.outlook.com").
#
# ----------------------
#
# Alternative options for retrieving similar/related information:
#
# eDiscovery/Content Search (no timeframe limit, but slow and clunky to use)
#
# Message trace logs (limited to 10 DAYS):
# Get-MessageTrace -MessageId XSERVER1Tbj1Dj2C700000523@xserver1-ppp-.com| Get-MessageTraceDetail | Select MessageID, Date, Event, Action, Detail, Data | Out-GridView
#
# Historical message trace logs (limited to past 90 days):
# Start-HistoricalSearch -ReportTitle "Fabrikam Search" -StartDate 1/1/2023 -EndDate 1/7/2023 -MessageID $INetMessageID
#
# Get-Message (Exchange On-prem ONLY)
# Get-messagetrackinglog -MessageID $INetMessageID (Exchange On-prem ONLY)
#
# ----------------------
#
# Usage:
# powershell -executionpolicy bypass -f .\Search-MailboxMessage.ps1 -InputFile ".\QueryList.txt"
#
# powershell -executionpolicy bypass -f .\Search-MailboxMessage.ps1 -InputFile ".\QueryList.txt" -OutputPath "C:\temp" -TenantID "XXX-XXX-XXX" -ClientID "XXX-XXX-XXX" -ClientSecret "XxXxXxX" -UserID "XXX@ZZZ.com"
#
# powershell -executionpolicy bypass -f .\Search-MailboxMessage.ps1 -InputQuery "Phishing Message Subject" -OutputPath "C:\temp" -SearchParam "Subject" -TenantID "XXX-XXX-XXX" -ClientID "XXX-XXX-XXX" -ClientSecret "XxXxXxX" -UserID "XXX@ZZZ.com"
#
# Run with already existing connection to M365 tenant through
# PowerShell modules, or already registered Enterprise Application.
#
# Use with DropShim.bat to allow drag-and-drop processing of an Internet Message ID list.
# Recommended workflow is to run this script initially from the command line in the course of and investigation
# where it will create Entra app, and subsequently use the shim drag-and-drop for message retrieval.
#
# Uses Microsoft Graph commands.
# Minimally required tenant role(s) FOR PROVISIONING ONLY: "Application Administrator" + "Privileged Role Admin" (for AppRoleAssignment).
# Retrieval-only runs (saved, non-expired secret present) need no tenant provisioning role.
#
#comp #m365 #security #bec #script #irscript #powershell #graph #message #retrieve #search
#Requires -Version 5.1
#Requires -Modules Microsoft.Graph.Authentication, Microsoft.Graph.Applications
[CmdletBinding(SupportsShouldProcess)]
Param (
[string]$InputFile,
[string]$InputQuery,
[string]$OutputPath = "Default",
[string]$SearchParam = "MessageID",
[string]$TenantID,
[string]$ClientID,
[string]$ClientSecret,
[string]$AppInfo = "MailAppInfo.json",
[int]$SecretValidityDays = 10, # Lifetime of a newly created client secret, in days.
[int]$SecretRenewMarginMinutes = 120, # Renew a saved secret if it expires within this many minutes.
[string]$UserId, # UPN of mailbox to search
[string]$scriptName = "Search-MailboxMessage",
[string]$ScriptVersion = "v5.1.0 - DEF CON edition - last updated 2026-07-31",
[string]$Priority = "Normal",
[string]$DebugPreference = "SilentlyContinue",
[string]$VerbosePreference = "SilentlyContinue",
[string]$InformationPreference = "Continue",
[string]$logFileFolderPath = "C:\temp\log",
[string]$ComputerName = $env:computername,
[string]$ScriptUserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name,
[string]$logFilePrefix = "$scriptName" + "_" + "$ComputerName" + "_",
[string]$logFileDateFormat = "yyyyMMdd_HHmmss",
[int]$logFileRetentionDays = 30,
[string]$Encoding = "utf8NoBOM", # PS 5 & 7: "Ascii" (7-bit), "BigEndianUnicode" (UTF-16 big-endian), "BigEndianUTF32", "Oem", "Unicode" (UTF-16 little-endian), "UTF32" (little-endian), "UTF7", "UTF8" (PS 5: BOM, PS 7: NO BOM). PS 7: "ansi", "utf8BOM", "utf8NoBOM",
[switch]$ReadOnly,
[switch]$NoExplorer
)
#region initialization
if ($PSVersionTable.PSVersion.Major -eq 5 -and ($Encoding -eq "utf8bom" -or $Encoding -eq "utf8nobom")) { $Encoding = "utf8" }
function Get-TimeStamp {
param(
[switch]$NoWrap,
[switch]$Utc
)
$dt = Get-Date
if ($Utc -eq $true) {
$dt = $dt.ToUniversalTime()
}
$str = "{0:yyyy-MM-dd} {0:HH:mm:ss}" -f $dt
if ($NoWrap -ne $true) {
$str = "[$str]"
}
return $str
}
if ($logFileFolderPath -ne "") {
if (!(Test-Path -PathType Container -Path $logFileFolderPath)) {
Write-Output "$(Get-TimeStamp) Creating directory $logFileFolderPath" | Out-Null
New-Item -ItemType Directory -Force -Path $logFileFolderPath | Out-Null
} else {
$DatetoDelete = $(Get-Date).AddDays(- $logFileRetentionDays)
Get-ChildItem $logFileFolderPath | Where-Object { $_.Name -like "*$logFilePrefix*" -and $_.LastWriteTime -lt $DatetoDelete } | Remove-Item | Out-Null
}
$logFilePath = $logFileFolderPath + "\$logFilePrefix" + (Get-Date -Format $logFileDateFormat) + ".LOG"
}
function Assert-M365Connection {
<#
.SYNOPSIS
Checks for active Exchange Online and/or MS Graph connections and attempts to connect if missing.
Scoped to the minimum permissions required by this script.
#>
param(
[switch]$RequireEXO,
[switch]$RequireGraph,
[switch]$RequireIPPS,
[string[]]$GraphScopes
)
if ($RequireEXO) {
$exoConnected = $false
try { $exoConnected = [bool](Get-ConnectionInformation -ErrorAction SilentlyContinue) } catch {}
if (-not $exoConnected) {
Write-Output "Exchange Online not connected. Attempting connection..."
try {
Connect-ExchangeOnline -ShowBanner:$false
Write-Output "Exchange Online connected."
} catch {
Write-Error "Failed to connect to Exchange Online: $_"
exit 1
}
} else {
Write-Output "Exchange Online connection verified."
}
}
if ($RequireIPPS) {
$ippsConnected = $false
try { $ippsConnected = [bool](Get-ConnectionInformation -ErrorAction SilentlyContinue | Where-Object { $_.ConnectionUri -match "compliance" }) } catch {}
if (-not $ippsConnected) {
Write-Output "Security & Compliance (IPPS) not connected. Attempting connection..."
try {
Connect-IPPSSession -ShowBanner:$false
Write-Output "IPPS connected."
} catch {
Write-Error "Failed to connect to IPPS: $_"
exit 1
}
} else {
Write-Output "IPPS connection verified."
}
}
if ($RequireGraph) {
$graphContext = $null
try { $graphContext = Get-MgContext -ErrorAction SilentlyContinue } catch {}
if (-not $graphContext) {
Write-Output "MS Graph not connected. Attempting connection with scopes: $($GraphScopes -join ', ')..."
try {
Connect-MgGraph -Scopes $GraphScopes -NoWelcome
Write-Output "MS Graph connected."
} catch {
Write-Error "Failed to connect to MS Graph: $_"
exit 1
}
} else {
# Verify required scopes are present
$currentScopes = $graphContext.Scopes
$missingScopes = $GraphScopes | Where-Object { $_ -notin $currentScopes }
if ($missingScopes) {
Write-Output "MS Graph connected but missing scopes: $($missingScopes -join ', '). Reconnecting..."
try {
Connect-MgGraph -Scopes $GraphScopes -NoWelcome
Write-Output "MS Graph reconnected with required scopes."
} catch {
Write-Warning "Could not reconnect with required scopes. Some operations may fail."
}
} else {
Write-Output "MS Graph connection verified with required scopes."
}
}
}
}
$sw = [Diagnostics.StopWatch]::StartNew()
$RunStart = Get-Date
$ReadScopes = @("Application.Read.All", "Domain.Read.All", "Organization.Read.All", "User.Read.All")
$WriteScopes = @("Application.ReadWrite.All", "AppRoleAssignment.ReadWrite.All", "DelegatedPermissionGrant.ReadWrite.All")
$date = Get-Date -Format "yyyyMMddHHmmss"
# ---- Early credential resolution (before any Microsoft Graph sign-in) ----
# If a good app registration + non-expired client secret is already available (passed as parameters, or saved in
# MailAppInfo.json from a previous run), we skip the interactive Graph connection entirely so routine retrieval
# runs need NO provisioning permissions. Graph is contacted only to create/renew the app or secret, to resolve
# the primary domain (non -InputFile path), or to enumerate mailboxes for an all-mailbox search.
$CredSource = "none"
$SecretExpiry = $null
# With -InputFile we can locate MailAppInfo.json without touching Graph (paths derive from the file location).
if ($InputFile) {
$OutputPath = $InputFile | Split-Path -Parent | Split-Path -Parent
$DomainName = $InputFile | Split-Path -Parent | Split-Path -Leaf
}
if ($TenantID -and $ClientID -and $ClientSecret) {
# Command-line credentials take precedence. Expiry is unknown, so treat as usable; Get-MailAppToken's retry
# (and, ultimately, a thrown error) surfaces a genuinely bad/expired secret.
$CredSource = "parameters"
} elseif ($OutputPath -and $DomainName) {
$EarlyAppInfo = Get-Content "$OutputPath\$DomainName\$AppInfo" -ErrorAction SilentlyContinue | ConvertFrom-Json
if ($EarlyAppInfo -and $EarlyAppInfo.tenantid -and $EarlyAppInfo.clientid -and $EarlyAppInfo.clientsecret) {
$TenantID = $EarlyAppInfo.tenantid
$ClientID = $EarlyAppInfo.clientid
$ClientSecret = $EarlyAppInfo.clientsecret
if ($EarlyAppInfo.secretexpiry) { try { $SecretExpiry = [datetime]$EarlyAppInfo.secretexpiry } catch { $SecretExpiry = $null } }
$CredSource = "MailAppInfo.json"
}
}
# A saved secret is "usable" if all three values are present AND either no expiry is recorded (legacy file) or it
# is not within the renewal margin of expiring.
$RenewCutoff = (Get-Date).AddMinutes($SecretRenewMarginMinutes)
$HaveUsableAppCreds = $false
if ($TenantID -and $ClientID -and $ClientSecret) {
if ($CredSource -eq "parameters") {
$HaveUsableAppCreds = $true
} elseif (-not $SecretExpiry) {
$HaveUsableAppCreds = $true # Legacy MailAppInfo.json without recorded expiry - assume usable; retry logic catches a dead secret.
} elseif ($SecretExpiry -gt $RenewCutoff) {
$HaveUsableAppCreds = $true
} else {
Write-Output "Saved client secret expires $($SecretExpiry.ToString('yyyy-MM-dd HH:mm:ss')) (within $SecretRenewMarginMinutes-minute renewal window). Will renew via Microsoft Graph." | Tee-Object -FilePath $logFilePath -Append
}
}
# ---- Microsoft Graph connection (skipped when usable app credentials already exist) ----
$GraphConnected = $false
if ($HaveUsableAppCreds -and $DomainName) {
# Enough to run offline: we have credentials AND we already know the output domain folder.
Write-Output "Usable app credentials present (source: $CredSource). Skipping interactive Microsoft Graph sign-in - no provisioning permissions required for this run." | Tee-Object -FilePath $logFilePath -Append
} elseif ($HaveUsableAppCreds) {
# Have credentials but still need Graph (read-only) to resolve the primary domain / validate users.
Write-Output "Usable app credentials present (source: $CredSource) but primary domain must be resolved. Connecting with read-only Graph scopes (no provisioning permissions)." | Tee-Object -FilePath $logFilePath -Append
Assert-M365Connection -RequireGraph -GraphScopes $ReadScopes
$GraphConnected = $true
} else {
# No usable credentials - connect with the scopes needed to create/renew the app + secret (or read-only if -ReadOnly).
if ($ReadOnly) {
Write-Output "-ReadOnly specified: requesting read-only Graph scopes; app registration/provisioning will be skipped." | Tee-Object -FilePath $logFilePath -Append
Assert-M365Connection -RequireGraph -GraphScopes $ReadScopes
} else {
Assert-M365Connection -RequireGraph -GraphScopes ($ReadScopes + $WriteScopes)
}
$GraphConnected = $true
}
Write-Output "$scriptName started on $ComputerName by $ScriptUserName at $(Get-TimeStamp)" | Tee-Object -FilePath $logFilePath -Append
$process = Get-Process -Id $pid
Write-Output "Setting process priority to `"$Priority`"" | Tee-Object -FilePath $logFilePath -Append
$process.PriorityClass = $Priority
#endregion initialization
$ScopeCheck = if ($GraphConnected) { (Get-MgContext).Scopes } else { @() }
$WriteCapable = $GraphConnected -and (-not $ReadOnly) -and ($ScopeCheck -contains "Application.ReadWrite.All")
if ($GraphConnected -and -not $WriteCapable) {
Write-Output "READ-ONLY GRAPH: write scope 'Application.ReadWrite.All' not granted$(if ($ReadOnly) { ' (-ReadOnly specified)' } else { '' }). If no usable app credentials are available, the PowerShellMailRead app registration/secret will NOT be created and app-based mailbox search will be unavailable." | Tee-Object -FilePath $logFilePath -Append
}
## Resolve OutputPath / DomainName.
if (!$InputFile) {
# Only try to escalate to write scopes when we actually need to provision.
if ($GraphConnected -and -not $HaveUsableAppCreds) {
Get-MgContext
if (-not $ReadOnly -and $ScopeCheck -notcontains "Application.ReadWrite.All") {
Write-Output "Write scope 'Application.ReadWrite.All' not present. Attempting to reconnect with required read + write scopes..." | Tee-Object -FilePath $logFilePath -Append
try { Connect-MgGraph -Scopes ($ReadScopes + $WriteScopes) -NoWelcome } catch { Write-Warning "Reconnect for write scopes failed: $($_.Exception.Message)" }
$ScopeCheck = (Get-MgContext).Scopes
$WriteCapable = (-not $ReadOnly) -and ($ScopeCheck -contains "Application.ReadWrite.All")
}
}
## If OutputPath variable is not defined, prompt for it
if (!$OutputPath) {
Write-Output ""
$OutputPath = Read-Host "Enter the output base path, e.g. $($env:userprofile)\Desktop\Investigation (default)" | Tee-Object -FilePath $logFilePath -Append
If ($OutputPath -eq '') { $OutputPath = "$($env:userprofile)\Desktop\Investigation" }
Write-Output "Output base path will be in $OutputPath" | Tee-Object -FilePath $logFilePath -Append
} elseif ($OutputPath -eq 'Default') {
Write-Output ""
$OutputPath = "$($env:userprofile)\Desktop\Investigation"
Write-Output "Output base path will be in $OutputPath" | Tee-Object -FilePath $logFilePath -Append
}
## If OutputPath does not exist, create it
$CheckOutputPath = Get-Item $OutputPath -ErrorAction SilentlyContinue
if (!$CheckOutputPath) {
Write-Output ""
Write-Output "Output path does not exist. Directory will be created." | Tee-Object -FilePath $logFilePath -Append
mkdir $OutputPath
}
## Get Primary Domain Name for output subfolder
if ($GraphConnected) {
$PrimaryDomain = Get-MgDomain | Where-Object { $_.isdefault -eq $True } | Select-Object -Property ID
if ($PrimaryDomain) {
$DomainName = $PrimaryDomain.ID
} else {
$DomainName = "DefaultOutput"
}
} elseif (-not $DomainName) {
$DomainName = "DefaultOutput"
}
} else {
# OutputPath / DomainName were already derived from -InputFile above; no Get-MgDomain needed.
}
$CheckSubDir = Get-Item $OutputPath\$DomainName\Messages_$date -ErrorAction SilentlyContinue
if (!$CheckSubDir) {
Write-Output ""
Write-Output "Domain/Messages sub-directory does not exist. Sub-directory `"$DomainName\Messages_$date`" will be created." | Tee-Object -FilePath $logFilePath -Append
mkdir $OutputPath\$DomainName\Messages_$date
}
Write-Output "Domain/Messages sub-directory will be `"$DomainName\Messages_$date`"" | Tee-Object -FilePath $logFilePath -Append
## If UserId variable is not defined, prompt for it
if (!$UserId) {
Write-Output ""
$UserId = Read-Host 'Enter the UPN (email address) of the mailbox(s) to search/retrieve messages from (separate multiple with commas, leave blank to search all mailboxes)'
}
## Searching ALL mailboxes requires Graph (to enumerate users). Connect read-only if we skipped sign-in.
if (([string]::IsNullOrEmpty($UserId)) -and -not $GraphConnected) {
Write-Output "`nSearching ALL mailboxes requires a Microsoft Graph connection to enumerate users. Connecting with read-only scopes..." | Tee-Object -FilePath $logFilePath -Append
Assert-M365Connection -RequireGraph -GraphScopes $ReadScopes
$GraphConnected = $true
$ScopeCheck = (Get-MgContext).Scopes
}
if (([string]::IsNullOrEmpty($UserId))) {
if ($GraphConnected -and ($ScopeCheck -contains "User.Read.All" -or $ScopeCheck -contains "User.ReadWrite.All")) {
Write-Output "`nWill attempt to search ALL licensed mailboxes for each query. This could take a long time..." | Tee-Object -FilePath $logFilePath -Append
$UserId = "ALL"
$UserList = Get-MgUser -All -Property "Id,DisplayName,UserPrincipalName,AssignedLicenses"
$LicensedUsers = $UserList | Where-Object { $_.AssignedLicenses.Count -gt 0 }
$UnlicensedUsers = $UserList | Where-Object { $_.AssignedLicenses.Count -eq 0 }
Write-Output "`nList of licensed users on tenant:" | Tee-Object -FilePath $logFilePath -Append
$licensedUsers | Select-Object DisplayName, UserPrincipalName, ID | Tee-Object -FilePath $logFilePath -Append
Write-Output "`nThere are $($LicensedUsers.count) licensed users on tenant." | Tee-Object -FilePath $logFilePath -Append
$LicensedUsers = $LicensedUsers | Select-Object -ExpandProperty UserPrincipalName
} else {
Write-Output "`nNot connected to graph with needed scopes. Ending." | Tee-Object -FilePath $logFilePath -Append
exit 91
}
} else {
$UserIds = $UserId -split ','
if ($GraphConnected -and ($ScopeCheck -contains "User.Read.All" -or $ScopeCheck -contains "User.ReadWrite.All")) {
Write-Output "Checking tenant for specified licensed user(s)..." | Tee-Object -FilePath $logFilePath -Append
$LicensedUsers = @()
ForEach ($Id in $UserIds) {
$LicensedUsers = $LicensedUsers + $(Get-MgUser -All -Property "Id,DisplayName,UserPrincipalName,AssignedLicenses" | Where-Object { $_.UserPrincipalName -eq $Id -and $_.AssignedLicenses.Count -gt 0})
}
if ($LicensedUsers) {
Write-Output "Licensed user(s) found in tenant." | Tee-Object -FilePath $logFilePath -Append
$LicensedUsers
$LicensedUsers = $LicensedUsers | Select-Object -ExpandProperty UserPrincipalName
} else {
Write-Output "Licensed user not found in tenant." | Tee-Object -FilePath $logFilePath -Append
}
} else {
Write-Output "Graph not connected (or missing User.Read.All). Assuming UPN(s) are correct..." | Tee-Object -FilePath $logFilePath -Append
$LicensedUsers = $UserIds
}
}
if (!$LicensedUsers) {
Write-Output "No licensed users listed. Ending." | Tee-Object -FilePath $logFilePath -Append
exit 92
}
if ($SearchParam) {
Write-Output "Will search using '$SearchParam' query type"
} else {
Write-Output "`nEnter query type ('MessageID', 'Sender', 'Subject', 'SentAfter') to use"
$SearchParam = Read-Host "or leave blank to use default 'MessageID' search"
if ($SearchParam.length -eq 0) {
$SearchParam = 'MessageID'
}
}
if ($inputFile) {
Write-Output "Reading '$InputFile' for query list..."
$QueryList = Get-Content $inputFile
} elseif ($InputQuery) {
Write-Output "Will search for '$InputQuery'"
$QueryList = $InputQuery
} else {
Write-Output "`nEnter search string of type '$SearchParam' to search individually (be sure to include angle brackets on MessageIDs),"
Write-Output "enter filename of query list located in $OutputPath\$DomainName\, preceded by an '*' to load specific list,"
$QueryList = Read-Host "or leave blank to attempt to read default file - $OutputPath\$DomainName\MessageIDList.txt"
if ($QueryList.length -gt 0 -and $QueryList[0] -eq "*") {
$QueryList = $QueryList.Substring(1)
if (Test-Path "$OutputPath\$DomainName\$QueryList") {
$QueryList = Get-Content "$OutputPath\$DomainName\$QueryList"
} else {
Write-Output "Unable to load file."
}
} elseif ($QueryList.length -eq 0 -and $(Test-Path "$OutputPath\$DomainName\MessageIDList.txt")) {
$QueryList = Get-Content "$OutputPath\$DomainName\MessageIDList.txt"
}
}
if ($QueryList.count -eq 0) {
Write-Output "Query list not specified. Ending." | Tee-Object -FilePath $logFilePath -Append
exit 95
}
Write-Output "`nFirst entry of query list:" | Tee-Object -FilePath $logFilePath -Append
$QueryList | Select-Object -first 1 | Tee-Object -FilePath $logFilePath -Append
Write-Output "`nQuery list is $($QueryList.count) items long..." | Tee-Object -FilePath $logFilePath -Append
function Parse-JWTtoken {
# https://jwt.io/
[cmdletbinding()]
param([Parameter(Mandatory=$true)][string]$token)
#Validate as per https://tools.ietf.org/html/rfc7519
#Access and ID tokens are fine, Refresh tokens will not work
if (!$token.Contains(".") -or !$token.StartsWith("eyJ")) { Write-Error "Invalid token" -ErrorAction Stop }
#Header
$tokenheader = $token.Split(".")[0].Replace('-', '+').Replace('_', '/')
#Fix padding as needed, keep adding "=" until string length modulus 4 reaches 0
while ($tokenheader.Length % 4) { Write-Output "Invalid length for a Base-64 char array or string, adding ="; $tokenheader += "=" }
Write-Output "Base64 encoded (padded) header:"
Write-Output $tokenheader
#Convert from Base64 encoded string to PSObject all at once
Write-Output "Decoded header:"
[System.Text.Encoding]::ASCII.GetString([system.convert]::FromBase64String($tokenheader)) | ConvertFrom-Json | fl | Out-Default
#Payload
$tokenPayload = $token.Split(".")[1].Replace('-', '+').Replace('_', '/')
#Fix padding as needed, keep adding "=" until string length modulus 4 reaches 0
while ($tokenPayload.Length % 4) { Write-Output "Invalid length for a Base-64 char array or string, adding ="; $tokenPayload += "=" }
Write-Output "Base64 encoded (padded) payoad:"
Write-Output $tokenPayload
#Convert to Byte array
$tokenByteArray = [System.Convert]::FromBase64String($tokenPayload)
#Convert to string array
$tokenArray = [System.Text.Encoding]::ASCII.GetString($tokenByteArray)
Write-Output "Decoded array in JSON format:"
Write-Output $tokenArray
#Convert from JSON to PSObject
$tokobj = $tokenArray | ConvertFrom-Json
Write-Output "Decoded Payload:"
return $tokobj
}
function Get-MailAppToken {
# Retrieve an app-only (client-credentials) Microsoft Graph access token for the given app registration.
# Retries on AADSTS7000215 ("Invalid client secret") with exponential backoff, because a freshly created
# secret can take a short time to replicate across Entra before the token endpoint will honor it. A wrong
# or expired secret still surfaces after $MaxRetries so genuine failures are not masked forever.
param(
[Parameter(Mandatory = $true)][string]$TenantId,
[Parameter(Mandatory = $true)][string]$ClientId,
[Parameter(Mandatory = $true)][string]$ClientSecret,
[int]$MaxRetries = 6,
[int]$InitialDelaySeconds = 10
)
$AzureBody = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $ClientId
Client_Secret = $ClientSecret
}
$delay = $InitialDelaySeconds
for ($attempt = 1; $attempt -le $MaxRetries; $attempt++) {
try {
$tokenResponse = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$($TenantId)/oauth2/v2.0/token" -Body $AzureBody -ErrorAction Stop
return $tokenResponse.access_token
} catch {
$detail = if ($_.ErrorDetails.Message) { $_.ErrorDetails.Message } else { "$_" }
if ($detail -match "7000215" -and $attempt -lt $MaxRetries) {
Write-Output "Token attempt $attempt hit AADSTS7000215 (new secret not yet replicated). Waiting $delay s, then retrying..." | Tee-Object -FilePath $logFilePath -Append
Start-Sleep -Seconds $delay
$delay = [math]::Min($delay * 2, 60)
} else {
throw
}
}
}
}
function New-MailReadAppRegistration {
# Ensures the 'PowerShellMailRead' Entra app registration exists (creating it only if absent), attaches a
# fresh client secret (valid $SecretValidityDays days), ensures the service principal and Mail.Read/User.Read.All
# app-role grants are present (idempotently), writes MailAppInfo.json (including the secret expiry), and sets
# script-scope $TenantID/$ClientID/$ClientSecret/$SecretExpiry for client-credentials token acquisition.
#
# Only called when no usable (saved, non-expired) secret is available, so this is the create/renew path.
# The client ID is ALWAYS derived from the same $app object the secret is attached to. It is never re-fetched
# by display name, so duplicate 'PowerShellMailRead' registrations can no longer cause a secret/client-ID
# mismatch (the root cause of AADSTS7000215 on prior versions).
# Requires write access; honors -WhatIf/-Confirm via the calling script's SupportsShouldProcess (New-Mg* propagate).
# Variables for application
$appName = "PowerShellMailRead"
$supportedAccountTypes = "AzureADMyOrg"
$redirectUri = "http://localhost"
$desiredRoles = @("User.Read.All", "Mail.Read")
# https://graphpermissions.merill.net/permission/Mail.Read?tabs=apiv1%2CadministrativeUnit1
# --- 1. Resolve the app ONCE, server-side, and reuse if it already exists ---
$existingApps = @(Get-MgApplication -Filter "displayName eq '$appName'" -All)
if ($existingApps.Count -gt 1) {
Write-Warning "Found $($existingApps.Count) app registrations named '$appName'. Reusing the oldest; consider removing the duplicates."
$app = $existingApps | Sort-Object CreatedDateTime | Select-Object -First 1
Write-Output "Reusing existing app '$appName' (AppId $($app.AppId))." | Tee-Object -FilePath $logFilePath -Append
} elseif ($existingApps.Count -eq 1) {
$app = $existingApps[0]
Write-Output "Reusing existing app '$appName' (AppId $($app.AppId))." | Tee-Object -FilePath $logFilePath -Append
} else {
Write-Output "`nApplication not found. Creating app registration '$appName' with Mail.Read permissions..." | Tee-Object -FilePath $logFilePath -Append
$app = New-MgApplication -DisplayName $appName -SignInAudience $supportedAccountTypes -Web @{ RedirectUris = @($redirectUri) }
}
# Keep $app as-is from here on. Never re-fetch it by display name.
# --- 2. Add a fresh secret (only reached when no usable saved secret exists) ---
$secretEnd = (Get-Date).AddDays($SecretValidityDays)
Write-Output "Creating client secret (expires $($secretEnd.ToString('yyyy-MM-dd HH:mm:ss')), $SecretValidityDays-day lifetime)..." | Tee-Object -FilePath $logFilePath -Append
$passwordCredential = @{
displayName = "ClientSecret-$(Get-Date -Format yyyyMMddHHmmss)"
endDateTime = $secretEnd
}
$secret = Add-MgApplicationPassword -ApplicationId $app.Id -PasswordCredential $passwordCredential
# --- 3. Ensure the service principal exists (reuse-safe) ---
$spn = Get-MgServicePrincipalByAppId -AppId $app.AppId -ErrorAction SilentlyContinue
if (-not $spn) {
Write-Output "Creating service principal for app..." | Tee-Object -FilePath $logFilePath -Append
$spn = New-MgServicePrincipal -AppId $app.AppId
}
# --- 4. Grant Mail.Read / User.Read.All app roles only if not already assigned (reuse-safe) ---
Write-Output "Ensuring API (application) permissions are granted..." | Tee-Object -FilePath $logFilePath -Append
$graphSp = Get-MgServicePrincipal -Filter "AppId eq '00000003-0000-0000-c000-000000000000'" # Microsoft Graph
$roleObjs = $graphSp.AppRoles | Where-Object { $_.Value -in $desiredRoles }
$existingAssignments = @(Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $spn.Id -ErrorAction SilentlyContinue)
foreach ($role in $roleObjs) {
if ($existingAssignments.AppRoleId -notcontains $role.Id) {
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $spn.Id -PrincipalId $spn.Id -ResourceId $graphSp.Id -AppRoleId $role.Id | Out-Null
Write-Output "Granted app role $($role.Value)." | Tee-Object -FilePath $logFilePath -Append
} else {
Write-Output "App role $($role.Value) already assigned." | Tee-Object -FilePath $logFilePath -Append
}
}
# --- 5. Persist and export using the SAME app object throughout (record expiry so future runs can reuse) ---
$TenantID = Get-MgOrganization | Select-Object -ExpandProperty Id
Write-Output "Exporting client app information to $AppInfo..." | Tee-Object -FilePath $logFilePath -Append
$MailAppInfo = [PSCustomObject]@{
'tenantid' = $TenantID
'clientid' = $app.AppId # from the SAME app the secret is attached to
'clientsecret' = $secret.SecretText
'secretexpiry' = $secretEnd.ToString('o')
}
if ($MailAppInfo) {
$MailAppInfo | ConvertTo-Json -Depth 100 | Out-File -FilePath "$OutputPath\$DomainName\MailAppInfo.json"
} else {
Write-Output "`$MailAppInfo is empty - skipping MailAppInfo output" | Tee-Object -FilePath $logFilePath -Append
}
$script:TenantID = $TenantID
$script:ClientID = $app.AppId
$script:ClientSecret = $secret.SecretText
$script:SecretExpiry = $secretEnd
}
function Get-MailboxMessageRecord {
# Searches one mailbox for one query string, records message metadata, saves the .eml body,
# and appends the resulting record to the script-scope $MessageInfoIndex.
param(
[Parameter(Mandatory = $true)][string]$Upn,
[Parameter(Mandatory = $true)]$QueryString,
[Parameter(Mandatory = $true)][string]$SearchParam,
[Parameter(Mandatory = $true)][hashtable]$AuthHeaders
)
if ($SearchParam -eq "MessageID") {
# Search for the message by "internetMessageId"
$SearchUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/?`$filter=internetMessageId eq '$QueryString'"
# https://graph.microsoft.com/v1.0/me/messages?$filter=internetMessageId eq 'Message_Id_Including_Brackets'
} elseif ($SearchParam -eq "Sender") {
# Search for the message by "address"
$SearchUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/?`$filter=sender/emailAddress/address eq $QueryString'"
# $SearchUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/?`$filter=sender/emailAddress/address eq '$SenderAddress'"
} elseif ($SearchParam -eq "Subject") {
# Search for the message by "Subject"
$SearchUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/?`$filter=subject eq '$QueryString'"
# $SearchUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/?`$filter=subject eq '$subject'"
} elseif ($SearchParam -eq "SentAfter") {
# Search for the message by "sentDateTime"
$SearchUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/?`$filter=sentDateTime ge $($QueryString.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ'))"
# $SearchUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/?`$filter=sentDateTime ge $($StartDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ'))"
} else {
Write-Output "`nInvalid search parameter '$SearchParam'. Ending"
exit 96
}
# DELETE message by "internetMessageId" - needs Mail.ReadWrite
# $SearchUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/?`$filter=internetMessageId eq '$QueryString'"
# $Response = Invoke-WebRequest -Method Delete -Uri $SearchUri -Headers $AuthHeaders
# $SearchUri = "https://graph.microsoft.com/v1.0/me/messages?$filter=subject eq '$subject' and sender/emailAddress/address eq '$SenderAddress' and sentDateTime ge $($StartDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ'))"
Write-Output "`nSearching for $($QueryString) in $($Upn)..." | Tee-Object -FilePath $logFilePath -Append
$SearchUri = [uri]::EscapeUriString($SearchUri)
$Response = ""
$Content = ""
$MessageContent = ""
# Query when using WebRequest or RestMethod with above auth header & token (instead of MgGraphRequest):
$Response = Invoke-WebRequest -Method Get -Uri $SearchUri -Headers $AuthHeaders
# $Response = Invoke-MgGraphRequest -Method Get -Uri $SearchUri
$Content = $Response.Content | Convertfrom-Json
if (!([string]::IsNullOrEmpty($Content.value.internetMessageId))) {
Write-Output "Message found. Parsing metadata & attempting to retrieving message content..." | Tee-Object -FilePath $logFilePath -Append
$OutputName = $Content.value.internetMessageId -replace "[^a-zA-Z0-9_\.,@ -]" # Make the output name as close to the original Message ID as possible given file name limitations
if ($Content.value.createdDateTime -ne $null) { $CreatedDateTime = $($Content.value.createdDateTime | Select-Object -First 1 | Get-Date).ToString('yyyy-MM-dd HH:mm:ss') } else { $CreatedDateTime = "N/A" }
if ($Content.value.sentDateTime -ne $null) { $SentDateTime = $($Content.value.sentDateTime | Select-Object -First 1 | Get-Date).ToString('yyyy-MM-dd HH:mm:ss') } else { $SentDateTime = "N/A" }
if ($Content.value.receivedDateTime -ne $null) { $ReceivedDateTime = $($Content.value.receivedDateTime | Select-Object -First 1 | Get-Date).ToString('yyyy-MM-dd HH:mm:ss') } else { $ReceivedDateTime = "N/A" }
if ($Content.value.sender.emailAddress -ne $null) { $Sender = $($Content.value.sender.emailAddress | Select-Object -First 1).address } else { $Sender = "N/A" }
if ($Content.value.from.emailAddress -ne $null) { $From = $($Content.value.from.emailAddress | Select-Object -First 1).address } else { $From = "N/A" }
if ($Content.value.toRecipients.emailAddress -ne $null) { $To = $($Content.value.toRecipients.emailAddress | foreach-object {$_.address}) -join "," } else { $To = "N/A" }
if ($Content.value.replyTo.emailAddress -ne $null) { $ReplyTo = $($Content.value.replyTo.emailAddress | Select-Object -First 1).address } else { $ReplyTo = "N/A" }
if ($Content.value.ccRecipients.emailAddress -ne $null) { $CC = $($Content.value.ccRecipients.emailAddress | foreach-object {$_.address}) -join "," } else { $CC = "N/A" }
if ($Content.value.bccRecipients.emailAddress -ne $null) { $BCC = $($Content.value.bccRecipients.emailAddress | foreach-object {$_.address}) -join "," } else { $BCC = "N/A" }
if ($Content.value.subject -ne $null) { $Subject = $Content.value.subject | Select-Object -First 1 } else { $Subject = "N/A" }
if ($Content.value.bodyPreview -ne $null) { $BodyPreview = $Content.value.bodyPreview | Select-Object -First 1 } else { $BodyPreview = "N/A" }
if ($Content.value.isRead -ne $null) { $IsRead = $($Content.value.isRead | Select-Object -First 1) } else { $IsRead = "N/A" }
if ($Content.value.isDraft -ne $null) { $IsDraft = $($Content.value.isDraft | Select-Object -First 1) } else { $IsDraft = "N/A" }
if ($Content.value.hasAttachments -ne $null) { $HasAttachments = $($Content.value.hasAttachments | Select-Object -First 1) } else { $HasAttachments = "N/A" }
if ($Content.value.flag.flagStatus -ne $null) { $FlagStatus = $Content.value.flag.flagStatus | Select-Object -First 1 } else { $FlagStatus = "N/A" }
if ($Content.value.webLink -ne $null) { $WebLink = $Content.value.webLink | Select-Object -First 1 } else { $WebLink = "N/A" }
if ($Content.value.internetMessageId -ne $null) { $InternetMessageId = $Content.value.internetMessageId | Select-Object -First 1 } else { $InternetMessageId = "N/A" }
if ($Content.value.id -ne $null) { $ID = $Content.value.id | Select-Object -First 1 } else { $ID = "" }
if ($Content.value.parentFolderId -ne $null) { $ParentFolderId = $Content.value.parentFolderId | Select-Object -First 1 } else { $ParentFolderId = "N/A" }
if ($Content.value.conversationId -ne $null) { $ConversationId = $Content.value.conversationId | Select-Object -First 1 } else { $ConversationId = "N/A" }
$MessageInfo = [PSCustomObject]@{
'InternetMessageId' = $InternetMessageId
'FileName' = $Upn + "_" + $OutputName
'Mailbox' = $Upn
'CreatedDateTime' = $CreatedDateTime
'SentDateTime' = $SentDateTime
'ReceivedDateTime' = $ReceivedDateTime
'Sender' = $Sender
'From' = $From
'To' = $To
'ReplyTo' = $ReplyTo
'CC' = $CC
'BCC' = $BCC
'Subject' = $Subject
'BodyPreview' = $BodyPreview
'IsRead' = $IsRead
'IsDraft' = $IsDraft
'HasAttachments' = $HasAttachments
'FlagStatus' = $FlagStatus
'WebLink' = $WebLink
'ID' = $ID
'ParentFolderId' = $ParentFolderId
'ConversationId' = $ConversationId
}
# If returned ID is not null get the message "value" and save the content to a file
if(!([string]::IsNullOrEmpty($ID))) {
$BodyUri = "https://graph.microsoft.com/v1.0/users/$($Upn)/messages/$($ID)/`$value"
$BodyUri = [uri]::EscapeUriString($BodyUri)
# Query when using WebRequest or RestMethod with above auth header & token (instead of MgGraphRequest):
$MessageContent = Invoke-WebRequest -Method Get -Uri $BodyUri -Headers $AuthHeaders -ErrorAction SilentlyContinue
# $MessageContent = Invoke-MgGraphRequest -Method Get -Uri $BodyUri -ErrorAction SilentlyContinue
if (!([string]::IsNullOrEmpty($MessageContent.Content))) {
Write-Output "Message message content retrieved." | Tee-Object -FilePath $logFilePath -Append
$MessageContent.Content | out-file "$OutputPath\$DomainName\Messages_$date\$($Upn)_$($OutputName).eml" -Encoding $Encoding
} else {
Write-Output "Message content unavailable." | Tee-Object -FilePath $logFilePath -Append
$MessageInfo.FileName = 'ContentUnavailable'
}
}
$script:MessageInfoIndex = $script:MessageInfoIndex + $MessageInfo
# $MessageInfo.InternetMessageId | fl
} else {
Write-Output "$($QueryString) not found in $Upn." | Tee-Object -FilePath $logFilePath -Append
$MessageInfo = [PSCustomObject]@{
'InternetMessageId' = $QueryString
'FileName' = 'NotFound'
'Mailbox' = $Upn
'CreatedDateTime' = ''
'SentDateTime' = ''
'ReceivedDateTime' = ''
'Sender' = ''
'From' = ''
'To' = ''
'ReplyTo' = ''
'CC' = ''
'BCC' = ''
'Subject' = ''
'BodyPreview' = ''
'IsRead' = ''
'IsDraft' = ''
'HasAttachments' = ''
'FlagStatus' = ''
'WebLink' = ''
'ID' = ''
'ParentFolderId' = ''
'ConversationId' = ''
}
$script:MessageInfoIndex = $script:MessageInfoIndex + $MessageInfo
}
}
# ---- Acquire Mail.Read app-only token once, before the search loops ----
# Credentials were already resolved during early credential resolution above ($TenantID/$ClientID/$ClientSecret,
# $HaveUsableAppCreds). Only provision (create/renew app + secret) when no usable secret is available.
$TokenTime = $null
$Token = $null
if (-not $HaveUsableAppCreds) {
if ($GraphConnected -and $WriteCapable) {
New-MailReadAppRegistration # Reuses existing app, adds a fresh secret, writes MailAppInfo.json (with expiry), sets script creds.
$HaveUsableAppCreds = $true
} else {
Write-Output "Unable to obtain token: no usable app credentials and cannot provision (read-only mode, or 'Application.ReadWrite.All' not granted). Provide -TenantID/-ClientID/-ClientSecret of an existing app, or re-run without -ReadOnly and consent write. Ending." | Tee-Object -FilePath $logFilePath -Append
exit 93
}
}
$Token = Get-MailAppToken -TenantId $TenantID -ClientId $ClientID -ClientSecret $ClientSecret
$TokenTime = [Diagnostics.StopWatch]::StartNew()
$AuthHeaders = @{
"Authorization" = "Bearer $($Token)"
"Content-type" = "application/json"
}
# Confirm the token carries the Mail.Read application role before searching.
$TokenRole = $(Parse-JWTtoken $Token).roles -contains "Mail.Read"
if (!$TokenRole) {
Write-Output "Missing M365 token role (Mail.Read) - correct and re-run." | Tee-Object -FilePath $logFilePath -Append
exit 95
}
$MessageInfoIndex = @()
foreach ($UPN in $LicensedUsers) {
foreach ($QueryString in $QueryList) {
# Refresh the app-only token if older than 30 minutes (avoids mid-run expiry on long searches).
if ($TokenTime.elapsed.totalseconds -gt 1800) {
Write-Output "`nRefreshing authentication token..." | Tee-Object -FilePath $logFilePath -Append
$Token = Get-MailAppToken -TenantId $TenantID -ClientId $ClientID -ClientSecret $ClientSecret
$TokenTime = [Diagnostics.StopWatch]::StartNew()
$AuthHeaders = @{
"Authorization" = "Bearer $($Token)"
"Content-type" = "application/json"
}
}
Get-MailboxMessageRecord -Upn $UPN -QueryString $QueryString -SearchParam $SearchParam -AuthHeaders $AuthHeaders
}
}
$OutputCSV = "$OutputPath\$DomainName\$($($UserId | Select-Object -First 1).Replace(',','-'))_MessageIndex_$($date).csv"
if ($MessageInfoIndex) {
$MessageInfoIndex | Export-Csv -Path $OutputCSV -NoTypeInformation -Append -Encoding $Encoding
} else {
Write-Output "`$MessageInfoIndex is empty - skipping output" | Tee-Object -FilePath $logFilePath -Append
}
if ((Test-Path -Path $OutputCSV) -eq "True") {
Write-Output `n" Message metadata index file is available at:" | Tee-Object -FilePath $logFilePath -Append
Write-Output $OutputCSV | Tee-Object -FilePath $logFilePath -Append
# $Prompt = New-Object -ComObject wscript.shell
# $UserInput = $Prompt.popup("Do you want to open output file?", 0, "Open Output File", 4)
# if ($UserInput -eq 6) {
# Invoke-Item "$OutputCSV"
# }
}
Write-Output "Search & retrieval of messages by ID complete." | Tee-Object -FilePath $logFilePath -Append
Write-Output "Seconds elapsed for script execution: $($sw.elapsed.totalseconds)" | Tee-Object -FilePath $logFilePath -Append
Write-Output "`nDone! Check output path for results." | Tee-Object -FilePath $logFilePath -Append
## ---- Run manifest & case-local log copy ----
try {
$RunStopUtc = (Get-Date).ToUniversalTime()
$ManifestGraphCtx = $null
try { $ManifestGraphCtx = Get-MgContext -ErrorAction SilentlyContinue } catch {}
$ManifestTenant = if ($ManifestGraphCtx -and $ManifestGraphCtx.TenantId) { $ManifestGraphCtx.TenantId } elseif ($TenantID) { $TenantID } elseif ($DomainName) { $DomainName } else { "(unknown)" }
$ManifestScopes = if ($ManifestGraphCtx -and $ManifestGraphCtx.Scopes) { ($ManifestGraphCtx.Scopes -join ", ") } else { "(no Microsoft Graph session - app-only token used)" }
$CaseFolder = if ($OutputPath -and $DomainName) { Join-Path $OutputPath $DomainName } else { $null }
$Manifest = New-Object System.Collections.Generic.List[string]
$Manifest.Add("")
$Manifest.Add("==================== RUN MANIFEST ====================")
$Manifest.Add("Script : $scriptName $ScriptVersion")
$Manifest.Add("Operator : $ScriptUserName")
$Manifest.Add("Computer : $ComputerName")
$Manifest.Add("Tenant : $ManifestTenant")
$Manifest.Add("Graph scopes : $ManifestScopes")
$Manifest.Add("Cred source : $CredSource")
$Manifest.Add("UTC start : $($RunStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))Z")
$Manifest.Add("UTC stop : $($RunStopUtc.ToString("yyyy-MM-dd HH:mm:ss"))Z")
$Manifest.Add("Elapsed seconds : $([math]::Round($sw.Elapsed.TotalSeconds, 2))")
$Manifest.Add("Output files (SHA256):")
if ($CaseFolder -and (Test-Path $CaseFolder)) {
$ProducedFiles = Get-ChildItem -Path $CaseFolder -File -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -ge $RunStart -and $_.Extension -ne ".LOG" }
if ($ProducedFiles) {
foreach ($pf in $ProducedFiles) {
$ph = try { (Get-FileHash -Path $pf.FullName -Algorithm SHA256 -ErrorAction Stop).Hash } catch { "(hash failed)" }
$Manifest.Add((" {0} {1}" -f $ph, $pf.FullName))
}
} else {
$Manifest.Add(" (no output files detected for this run)")
}
} else {
$Manifest.Add(" (no case output folder resolved)")
}
$Manifest.Add("=====================================================")
$Manifest | Tee-Object -FilePath $logFilePath -Append
if ($CaseFolder -and (Test-Path $CaseFolder) -and $logFilePath -and (Test-Path $logFilePath)) {
$CaseLogFolder = Join-Path $CaseFolder "log"
if (!(Test-Path $CaseLogFolder)) { New-Item -ItemType Directory -Force -Path $CaseLogFolder | Out-Null }
Copy-Item -Path $logFilePath -Destination (Join-Path $CaseLogFolder (Split-Path $logFilePath -Leaf)) -Force -ErrorAction SilentlyContinue
Write-Output "Run log copied to $CaseLogFolder" | Tee-Object -FilePath $logFilePath -Append
}
} catch {
Write-Warning "Run manifest / log copy step failed: $($_.Exception.Message)"
}
if (-not $NoExplorer) { Invoke-Item "$OutputPath\$DomainName" }
Exit