-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathMTL-Analyzer.ps1
1700 lines (1472 loc) · 104 KB
/
MTL-Analyzer.ps1
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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# MTL-Analyzer
#
# @author: Martin Willing
# @copyright: Copyright (c) 2025 Martin Willing. All rights reserved. Licensed under the MIT license.
# @contact: Any feedback or suggestions are always welcome and much appreciated - mwilling@lethal-forensics.com
# @url: https://lethal-forensics.com/
# @date: 2025-01-27
#
#
# ██╗ ███████╗████████╗██╗ ██╗ █████╗ ██╗ ███████╗ ██████╗ ██████╗ ███████╗███╗ ██╗███████╗██╗ ██████╗███████╗
# ██║ ██╔════╝╚══██╔══╝██║ ██║██╔══██╗██║ ██╔════╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║██╔════╝██║██╔════╝██╔════╝
# ██║ █████╗ ██║ ███████║███████║██║█████╗█████╗ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║███████╗██║██║ ███████╗
# ██║ ██╔══╝ ██║ ██╔══██║██╔══██║██║╚════╝██╔══╝ ██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║╚════██║██║██║ ╚════██║
# ███████╗███████╗ ██║ ██║ ██║██║ ██║███████╗ ██║ ╚██████╔╝██║ ██║███████╗██║ ╚████║███████║██║╚██████╗███████║
# ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═════╝╚══════╝
#
#
# Dependencies:
#
# ImportExcel v7.8.10 (2024-10-21)
# https://github.com/dfinke/ImportExcel
#
# IPinfo CLI 3.3.1 (2024-03-01)
# https://ipinfo.io/signup?ref=cli --> Sign up for free
# https://github.com/ipinfo/cli
#
# xsv v0.13.0 (2018-05-12)
# https://github.com/BurntSushi/xsv
#
#
# Tested on Windows 10 Pro (x64) Version 22H2 (10.0.19045.5371) and PowerShell 5.1 (5.1.19041.5369)
# Tested on Windows 10 Pro (x64) Version 22H2 (10.0.19045.5371) and PowerShell 7.5.0
#
#
#############################################################################################################################################################################################
#############################################################################################################################################################################################
<#
.SYNOPSIS
MTL-Analyzer - Automated Processing of M365 Message Trace Logs for DFIR
.DESCRIPTION
MTL-Analyzer.ps1 is a PowerShell script utilized to simplify the analysis of M365 Message Trace Logs extracted via "Microsoft Extractor Suite" by Invictus Incident Response.
https://github.com/invictus-ir/Microsoft-Extractor-Suite (Microsoft-Extractor-Suite v3.0.1)
https://microsoft-365-extractor-suite.readthedocs.io/en/latest/functionality/M365/MessageTraceLog.html
Single User Audit
.PARAMETER OutputDir
Specifies the output directory. Default is "$env:USERPROFILE\Desktop\MTL-Analyzer".
Note: The subdirectory 'MTL-Analyzer' is automatically created.
.PARAMETER Path
Specifies the path to the CSV-based input file (<UPN>-MTL.csv).
.EXAMPLE
PS> .\MTL-Analyzer.ps1
.EXAMPLE
PS> .\MTL-Analyzer.ps1 -Path "$env:USERPROFILE\Desktop\<UPN>-MTL.csv"
.EXAMPLE
PS> .\MTL-Analyzer.ps1 -Path "H:\Microsoft-Extractor-Suite\<UPN>-MTL.csv" -OutputDir "H:\Microsoft-Analyzer-Suite"
.NOTES
Author - Martin Willing
.LINK
https://lethal-forensics.com/
#>
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region CmdletBinding
[CmdletBinding()]
Param(
[String]$Path,
[String]$OutputDir
)
#endregion CmdletBinding
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Initialisations
# Set Progress Preference to Silently Continue
$OriginalProgressPreference = $Global:ProgressPreference
$Global:ProgressPreference = 'SilentlyContinue'
#endregion Initialisations
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Declarations
# Declarations
# Script Root
if ($PSVersionTable.PSVersion.Major -gt 2)
{
# PowerShell 3+
$SCRIPT_DIR = $PSScriptRoot
}
else
{
# PowerShell 2
$SCRIPT_DIR = Split-Path -Parent $MyInvocation.MyCommand.Definition
}
# Colors
Add-Type -AssemblyName System.Drawing
$script:Green = [System.Drawing.Color]::FromArgb(0,176,80) # Green
$script:Orange = [System.Drawing.Color]::FromArgb(255,192,0) # Orange
# Output Directory
if (!($OutputDir))
{
$script:OUTPUT_FOLDER = "$env:USERPROFILE\Desktop\MTL-Analyzer" # Default
}
else
{
if ($OutputDir -cnotmatch '.+(?=\\)')
{
Write-Host "[Error] You must provide a valid directory path." -ForegroundColor Red
Exit
}
else
{
$script:OUTPUT_FOLDER = "$OutputDir\MTL-Analyzer" # Custom
}
}
# Tools
# IPinfo CLI
$script:IPinfo = "$SCRIPT_DIR\Tools\IPinfo\ipinfo.exe"
# xsv
$script:xsv = "$SCRIPT_DIR\Tools\xsv\xsv.exe"
# Configuration File
if(!(Test-Path "$PSScriptRoot\Config.ps1"))
{
Write-Host "[Error] Config.ps1 NOT found." -ForegroundColor Red
}
else
{
. "$PSScriptRoot\Config.ps1"
}
#endregion Declarations
#############################################################################################################################################################################################
#region Header
# Check if the PowerShell script is being run with admin rights
if (!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
Write-Host "[Error] This PowerShell script must be run with admin rights." -ForegroundColor Red
Exit
}
# Check if PowerShell module 'ImportExcel' is installed
if (!(Get-Module -ListAvailable -Name ImportExcel))
{
Write-Host "[Error] Please install 'ImportExcel' PowerShell module." -ForegroundColor Red
Write-Host "[Info] Check out: https://github.com/evild3ad/Microsoft-Analyzer-Suite/wiki#setup"
Exit
}
# Windows Title
$DefaultWindowsTitle = $Host.UI.RawUI.WindowTitle
$Host.UI.RawUI.WindowTitle = "MTL-Analyzer - Automated Processing of M365 Message Trace Logs for DFIR"
# Flush Output Directory
if (Test-Path "$OUTPUT_FOLDER")
{
Get-ChildItem -Path "$OUTPUT_FOLDER" -Force -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse
New-Item "$OUTPUT_FOLDER" -ItemType Directory -Force | Out-Null
}
else
{
New-Item "$OUTPUT_FOLDER" -ItemType Directory -Force | Out-Null
}
# Add the required MessageBox class (Windows PowerShell)
Add-Type -AssemblyName System.Windows.Forms
# Function Get-FileSize
Function Get-FileSize() {
Param ([long]$Length)
If ($Length -gt 1TB) {[string]::Format("{0:0.00} TB", $Length / 1TB)}
ElseIf ($Length -gt 1GB) {[string]::Format("{0:0.00} GB", $Length / 1GB)}
ElseIf ($Length -gt 1MB) {[string]::Format("{0:0.00} MB", $Length / 1MB)}
ElseIf ($Length -gt 1KB) {[string]::Format("{0:0.00} KB", $Length / 1KB)}
ElseIf ($Length -gt 0) {[string]::Format("{0:0.00} Bytes", $Length)}
Else {""}
}
# Select Log File
if(!($Path))
{
Function Get-LogFile($InitialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.Filter = "Message Trace Log Files (*-MTL.csv)|*-MTL.csv|All Files (*.*)|*.*"
$OpenFileDialog.ShowDialog()
$OpenFileDialog.Filename
$OpenFileDialog.ShowHelp = $true
$OpenFileDialog.Multiselect = $false
}
$Result = Get-LogFile
if($Result -eq "OK")
{
$script:LogFile = $Result[1]
}
else
{
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
}
else
{
$script:LogFile = $Path
}
# Create a record of your PowerShell session to a text file
Start-Transcript -Path "$OUTPUT_FOLDER\Transcript.txt"
# Get Start Time
$startTime = (Get-Date)
# Logo
$Logo = @"
██╗ ███████╗████████╗██╗ ██╗ █████╗ ██╗ ███████╗ ██████╗ ██████╗ ███████╗███╗ ██╗███████╗██╗ ██████╗███████╗
██║ ██╔════╝╚══██╔══╝██║ ██║██╔══██╗██║ ██╔════╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║██╔════╝██║██╔════╝██╔════╝
██║ █████╗ ██║ ███████║███████║██║█████╗█████╗ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║███████╗██║██║ ███████╗
██║ ██╔══╝ ██║ ██╔══██║██╔══██║██║╚════╝██╔══╝ ██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║╚════██║██║██║ ╚════██║
███████╗███████╗ ██║ ██║ ██║██║ ██║███████╗ ██║ ╚██████╔╝██║ ██║███████╗██║ ╚████║███████║██║╚██████╗███████║
╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═════╝╚══════╝
"@
Write-Output ""
Write-Output "$Logo"
Write-Output ""
# Header
Write-Output "MTL-Analyzer - Automated Processing of M365 Message Trace Logs for DFIR"
Write-Output "(c) 2025 Martin Willing at Lethal-Forensics (https://lethal-forensics.com/)"
Write-Output ""
# Analysis date (ISO 8601)
$script:AnalysisDate = [datetime]::Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")
Write-Output "Analysis date: $AnalysisDate UTC"
Write-Output ""
# Create HashTable and import 'ASN-Whitelist.csv'
$script:AsnWhitelist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Whitelists\ASN-Whitelist.csv")
{
if([int](& $xsv count "$SCRIPT_DIR\Whitelists\ASN-Whitelist.csv") -gt 0)
{
Import-Csv "$SCRIPT_DIR\Whitelists\ASN-Whitelist.csv" -Delimiter "," | ForEach-Object { $AsnWhitelist_HashTable[$_.ASN] = $_.OrgName,$_.Info }
}
}
# Create HashTable and import 'ASN-Blacklist.csv'
$script:AsnBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv")
{
if([int](& $xsv count "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv") -gt 0)
{
Import-Csv "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv" -Delimiter "," | ForEach-Object { $AsnBlacklist_HashTable[$_.ASN] = $_.OrgName,$_.Info }
}
}
# Create HashTable and import 'Country-Blacklist.csv'
$script:CountryBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv")
{
if([int](& $xsv count "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv") -gt 0)
{
Import-Csv "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv" -Delimiter "," | ForEach-Object { $CountryBlacklist_HashTable[$_."Country Name"] = $_.Country }
}
}
#endregion Header
#############################################################################################################################################################################################
#region Analysis
# Message Trace Logs
Function Start-Processing {
# Input-Check
if (!(Test-Path "$LogFile"))
{
Write-Host "[Error] $LogFile does not exist." -ForegroundColor Red
Write-Host ""
Stop-Transcript
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
# Check File Extension
$Extension = [IO.Path]::GetExtension($LogFile)
if (!($Extension -eq ".csv" ))
{
Write-Host "[Error] No CSV File provided." -ForegroundColor Red
Stop-Transcript
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
# Check IPinfo CLI Access Token
if ("$Token" -eq "access_token")
{
Write-Host "[Error] No IPinfo CLI Access Token provided. Please add your personal access token to 'Config.ps1'" -ForegroundColor Red
Write-Host ""
Stop-Transcript
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
# UserId
$script:UserId = Import-Csv -Path "$LogFile" -Delimiter "," | Group-Object SenderAddress | Sort-Object Count -Descending | Select-Object Name,Count -First 1 | Select-Object -ExpandProperty Name
# Domain
$Domain = $UserId | ForEach-Object{($_ -split ".*@")[1]}
# Input Size
$InputSize = Get-FileSize((Get-Item "$LogFile").Length)
Write-Output "[Info] Total Input Size: $InputSize"
# Count rows of CSV (w/ thousands separators)
[int]$Count = & $xsv count "$LogFile"
$Rows = '{0:N0}' -f $Count
Write-Output "[Info] Total Lines: $Rows"
# Processing M365 Message Trace Logs
Write-Output "[Info] Processing M365 Message Trace Logs ($UserId) ..."
New-Item "$OUTPUT_FOLDER\MessageTraceLogs\CSV" -ItemType Directory -Force | Out-Null
New-Item "$OUTPUT_FOLDER\MessageTraceLogs\XLSX" -ItemType Directory -Force | Out-Null
# Check Timestamp Format
$Timestamp = (Import-Csv -Path "$LogFile" -Delimiter "," | Select-Object Received -First 1).Received
# de-DE
if ($Timestamp -match "\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}")
{
$script:TimestampFormat = "dd.MM.yyyy HH:mm:ss"
}
# en-US
if ($Timestamp -match "\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2} (AM|PM)")
{
$script:TimestampFormat = "M/d/yyyy h:mm:ss tt"
}
# Time Frame
$StartDate = (Import-Csv -Path "$LogFile" -Delimiter "," | Select-Object @{Name="Received";Expression={([DateTime]::ParseExact($_.Received, "$TimestampFormat", [cultureinfo]::InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"))}} | Sort-Object { $_.Received -as [datetime] } -Descending | Select-Object -Last 1).Received
$EndDate = (Import-Csv -Path "$LogFile" -Delimiter "," | Select-Object @{Name="Received";Expression={([DateTime]::ParseExact($_.Received, "$TimestampFormat", [cultureinfo]::InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"))}} | Sort-Object { $_.Received -as [datetime] } -Descending | Select-Object -First 1).Received
Write-Output "[Info] Log data from $StartDate UTC until $EndDate UTC"
# XLSX
# Untouched
if (Get-Module -ListAvailable -Name ImportExcel)
{
if (Test-Path "$LogFile")
{
if([int](& $xsv count -d "," "$LogFile") -gt 0)
{
$IMPORT = Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\XLSX\Untouched.xlsx" -NoHyperLinkConversion * -NoNumberConversion * -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "MTL-Untouched" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:N1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A, C-E and G-N
$WorkSheet.Cells["A:A"].Style.HorizontalAlignment="Center"
$WorkSheet.Cells["C:E"].Style.HorizontalAlignment="Center"
$WorkSheet.Cells["G:N"].Style.HorizontalAlignment="Center"
}
}
}
}
# File Size (XLSX)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\XLSX\Untouched.xlsx")
{
$Size = Get-FileSize((Get-Item "$OUTPUT_FOLDER\MessageTraceLogs\XLSX\Untouched.xlsx").Length)
Write-Output "[Info] File Size (XLSX) : $Size"
}
#############################################################################################################################################################################################
# Stats
New-Item "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound" -ItemType Directory -Force | Out-Null
New-Item "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound" -ItemType Directory -Force | Out-Null
New-Item "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Inbound" -ItemType Directory -Force | Out-Null
New-Item "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Outbound" -ItemType Directory -Force | Out-Null
# Total Messages
[int]$TotalMessages = (Import-Csv -Path "$LogFile" -Delimiter "," | Measure-Object).Count
$TotalMessagesCount = '{0:N0}' -f $TotalMessages
Write-Output "[Info] Total Messages: $TotalMessagesCount"
# Incoming Messages (RecipientAddress)
[int]$IncomingMessages = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.RecipientAddress -eq "$UserId" } | Measure-Object).Count
$IncomingMessagesCount = '{0:N0}' -f $IncomingMessages
# Incoming Messages (RecipientAddress) --> Internal
[int]$IncomingMessagesFromInternal = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.RecipientAddress -eq "$UserId"} | Where-Object {$_.SenderAddress -like "*$Domain"} | Measure-Object).Count
$IncomingMessagesFromInternalCount = '{0:N0}' -f $IncomingMessagesFromInternal
# Incoming Messages (RecipientAddress) --> External
[int]$IncomingMessagesFromExternal = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.RecipientAddress -eq "$UserId"} | Where-Object {$_.SenderAddress -notlike "*$Domain"} | Measure-Object).Count
$IncomingMessagesFromExternalCount = '{0:N0}' -f $IncomingMessagesFromExternal
Write-Output "[Info] Incoming Messages: $IncomingMessagesCount (Internal: $IncomingMessagesFromInternalCount, External: $IncomingMessagesFromExternalCount)"
# Outgoing Messages (SenderAddress)
[int]$OutgoingMessages = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.SenderAddress -eq "$UserId" } | Measure-Object).Count
$OutgoingMessagesCount = '{0:N0}' -f $OutgoingMessages
# Outgoing Messages (SenderAddress) --> Internal
[int]$OutgoingMessagesToInternal = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.SenderAddress -eq "$UserId" } | Where-Object {$_.RecipientAddress -like "*$Domain" } | Measure-Object).Count
$OutgoingMessagesToInternalCount = '{0:N0}' -f $OutgoingMessagesToInternal
# Outgoing Messages (SenderAddress) --> External
[int]$OutgoingMessagesToExternal = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.SenderAddress -eq "$UserId" } | Where-Object {$_.RecipientAddress -notlike "*$Domain" } | Measure-Object).Count
$OutgoingMessagesToExternalCount = '{0:N0}' -f $OutgoingMessagesToExternal
Write-Output "[Info] Outgoing Messages: $OutgoingMessagesCount (Internal: $OutgoingMessagesToInternalCount, External: $OutgoingMessagesToExternalCount)"
# Subject (Inbound)
# CSV (Stats)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object Subject | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Group-Object Subject | Sort-Object Count -Descending | Select-Object @{Name='Subject'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Subject.csv" -NoTypeInformation -Encoding UTF8
[int]$Count = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object Subject | Sort-Object Subject -Unique | Measure-Object).Count
$SubjectCount = '{0:N0}' -f $Count
Write-Output "[Info] Subjects (Inbound): $SubjectCount"
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Subject.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Subject.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Subject.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Inbound\Subject.xlsx" -NoHyperLinkConversion * -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Subject (Inbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
}
}
}
# Subject / Status (Inbound)
# CSV (Stats)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object Subject | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Group-Object Subject,Status | Select-Object @{Name='Subject'; Expression={ $_.Values[0] }},@{Name='Status'; Expression={ $_.Values[1] }},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Subject-Status.csv" -NoTypeInformation -Encoding UTF8
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Subject-Status.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Subject-Status.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Subject-Status.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Inbound\Subject-Status.xlsx" -NoHyperLinkConversion * -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Subject (Inbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:D1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-D
$WorkSheet.Cells["B:D"].Style.HorizontalAlignment="Center"
}
}
}
# Subject (Outbound)
# CSV (Stats)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object Subject | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Group-Object Subject | Sort-Object Count -Descending | Select-Object @{Name='Subject'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Subject.csv" -NoTypeInformation -Encoding UTF8
$SubjectCount = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object Subject | Sort-Object Subject -Unique | Measure-Object).Count
Write-Output "[Info] Subjects (Outbound): $SubjectCount"
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Subject.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Subject.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Subject.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Outbound\Subject.xlsx" -NoHyperLinkConversion * -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Subject (Outbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - Count
$LastRow = $WorkSheet.Dimension.End.Row
Add-ConditionalFormatting -Address $WorkSheet.Cells["A2:C$LastRow"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue '=$B2>=75' -BackgroundColor "Red" # 75x outgoing messages with the same 'Subject'
}
}
}
# Subject / Status (Outbound)
# CSV (Stats)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object Subject | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Group-Object Subject,Status | Select-Object @{Name='Subject'; Expression={ $_.Values[0] }},@{Name='Status'; Expression={ $_.Values[1] }},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Subject-Status.csv" -NoTypeInformation -Encoding UTF8
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Subject-Status.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Subject-Status.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Subject-Status.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Outbound\Subject-Status.xlsx" -NoHyperLinkConversion * -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Subject (Outbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:D1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-D
$WorkSheet.Cells["B:D"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - Count
$LastRow = $WorkSheet.Dimension.End.Row
Add-ConditionalFormatting -Address $WorkSheet.Cells["A2:D$LastRow"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue '=$C2>=75' -BackgroundColor "Red" # 75x outgoing messages with the same 'Subject'
}
}
}
# MessageId (Inbound)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object MessageId | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Group-Object MessageId | Sort-Object Count -Descending | Select-Object @{Name='MessageId'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\MessageIds.csv" -NoTypeInformation -Encoding UTF8
$MessageIdCount = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object MessageId | Sort-Object MessageId -Unique | Measure-Object).Count
Write-Output "[Info] MessageIds (Inbound): $MessageIdCount"
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\MessageIds.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\MessageIds.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\MessageIds.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Inbound\MessageIds.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "MessageId (Outbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
}
}
}
# MessageId (Outbound)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object MessageId | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Group-Object MessageId | Sort-Object Count -Descending | Select-Object @{Name='MessageId'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\MessageIds.csv" -NoTypeInformation -Encoding UTF8
$MessageIdCount = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object MessageId | Sort-Object MessageId -Unique | Measure-Object).Count
Write-Output "[Info] MessageIds (Outbound): $MessageIdCount"
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\MessageIds.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\MessageIds.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\MessageIds.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Outbound\MessageIds.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "MessageId (Outbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
}
}
}
# MessageTraceId (Inbound)
# CSV (Stats)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object MessageTraceId | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Group-Object MessageTraceId | Sort-Object Count -Descending | Select-Object @{Name='MessageTraceId'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\MessageTraceIds.csv" -NoTypeInformation -Encoding UTF8
$MessageTraceIdCount = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object MessageTraceId | Sort-Object MessageTraceId -Unique | Measure-Object).Count
Write-Output "[Info] MessageTraceIds (Inbound): $MessageTraceIdCount"
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\MessageTraceIds.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\MessageTraceIds.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\MessageTraceIds.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Inbound\MessageTraceIds.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "MessageTraceId (Inbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
}
}
}
# MessageTraceId (Outbound)
# CSV (Stats)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object MessageTraceId | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Group-Object MessageTraceId | Sort-Object Count -Descending | Select-Object @{Name='MessageTraceId'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\MessageTraceIds.csv" -NoTypeInformation -Encoding UTF8
$MessageTraceIdCount = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object MessageTraceId | Sort-Object MessageTraceId -Unique | Measure-Object).Count
Write-Output "[Info] MessageTraceIds (Outbound): $MessageTraceIdCount"
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\MessageTraceIds.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\MessageTraceIds.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\MessageTraceIds.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Outbound\MessageTraceIds.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "MessageTraceId (Outbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
}
}
}
# Status (Inbound)
Write-Output "[Info] Tracking the Delivery Status of all Inbound Messages ..."
# CSV (Stats)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object Status | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Group-Object Status | Sort-Object Count -Descending | Select-Object @{Name='Status'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Status.csv" -NoTypeInformation -Encoding UTF8
[int]$Failed = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Where-Object {$_.Status -eq 'Failed' } | Measure-Object).Count
[int]$Delivered = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Where-Object {$_.Status -eq 'Delivered' } | Measure-Object).Count
[int]$FilteredAsSpam = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Where-Object {$_.Status -eq 'FilteredAsSpam' } | Measure-Object).Count
[int]$Quarantined = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Where-Object {$_.Status -eq 'Quarantined' } | Measure-Object).Count
$FailedCount = '{0:N0}' -f $Failed
$DeliveredCount = '{0:N0}' -f $Delivered
$FilteredAsSpamCount = '{0:N0}' -f $FilteredAsSpam
$QuarantinedCount = '{0:N0}' -f $Quarantined
Write-Output "[Info] Delivered (Inbound): $DeliveredCount"
Write-Output "[Info] Failed (Inbound): $FailedCount"
Write-Output "[Info] FilteredAsSpam (Inbound): $FilteredAsSpamCount"
Write-Output "[Info] Quarantined (Inbound): $QuarantinedCount"
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Status.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Status.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Inbound\Status.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Inbound\Status.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Status (Inbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
}
}
}
# Add Worksheet w/ Pie Chart (Inbound)
$ExcelChart = New-ExcelChartDefinition -XRange Status -YRange Count -ChartType Pie -ShowPercent -Title "Delivery Status (Inbound)" -LegendPosition Bottom
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Inbound\Status.xlsx" -Append -WorksheetName "Pie Chart" -ExcelChartDefinition $ExcelChart -AutoNameRange
# Status (Outbound)
Write-Output "[Info] Tracking the Delivery Status of all Outbound Messages ..."
# CSV (Stats)
$Total = (Import-Csv -Path "$LogFile" -Delimiter "," | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object Status | Measure-Object).Count
Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Group-Object Status | Sort-Object Count -Descending | Select-Object @{Name='Status'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Export-Csv -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Status.csv" -NoTypeInformation -Encoding UTF8
[int]$Failed = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Where-Object {$_.Status -eq 'Failed' } | Measure-Object).Count
[int]$Delivered = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Where-Object {$_.Status -eq 'Delivered' } | Measure-Object).Count
[int]$FilteredAsSpam = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Where-Object {$_.Status -eq 'FilteredAsSpam' } | Measure-Object).Count
[int]$Quarantined = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Where-Object {$_.Status -eq 'Quarantined' } | Measure-Object).Count
$FailedCount = '{0:N0}' -f $Failed
$DeliveredCount = '{0:N0}' -f $Delivered
$FilteredAsSpamCount = '{0:N0}' -f $FilteredAsSpam
$QuarantinedCount = '{0:N0}' -f $Quarantined
Write-Output "[Info] Delivered (Outbound): $DeliveredCount"
Write-Output "[Info] Failed (Outbound): $FailedCount"
Write-Output "[Info] FilteredAsSpam (Outbound): $FilteredAsSpamCount"
Write-Output "[Info] Quarantined (Outbound): $QuarantinedCount"
# XLSX (Stats)
if (Test-Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Status.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Status.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\MessageTraceLogs\Stats\CSV\Outbound\Status.csv" -Delimiter ","
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Outbound\Status.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Status (Outbound)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
}
}
}
# Add Worksheet w/ Pie Chart (Outbound)
$ExcelChart = New-ExcelChartDefinition -XRange Status -YRange Count -ChartType Pie -ShowPercent -Title "Delivery Status (Outbound)" -LegendPosition Bottom
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\MessageTraceLogs\Stats\XLSX\Outbound\Status.xlsx" -Append -WorksheetName "Pie Chart" -ExcelChartDefinition $ExcelChart -AutoNameRange
# Delivery Status
#
# https://learn.microsoft.com/en-us/exchange/monitoring/trace-an-email-message/message-trace-modern-eac#delivery-status
#
# Delivered - The message was successfully delivered to the intended destination.
# Expanded - A distribution group recipient was expanded before delivery to the individual members of the group.
# Failed - The message wasn't delivered.
# FilteredAsSpam - The message was identified as spam, and was rejected or blocked (not quarantined).
# Pending - Delivery of the message is being attempted or reattempted.
# Quarantined - The message was quarantined (as spam, bulk mail, or phishing).
# Resolved - The message was redirected to a new recipient address based on an Active Directory look up. When this event happens, the original recipient address is listed in a separate row in the message trace along with the final delivery status for the message.
}
Start-Processing
#############################################################################################################################################################################################
Function Get-IPLocation {
# Count IP addresses
Write-Output "[Info] Parsing Message Trace Logs for FromIP Property ..."
New-Item "$OUTPUT_FOLDER\FromIP" -ItemType Directory -Force | Out-Null
$Data = Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Select-Object -ExpandProperty FromIP | Where-Object { $_.Trim() -ne "" }
$Unique = $Data | Sort-Object -Unique
$Unique | Out-File "$OUTPUT_FOLDER\FromIP\IP-All.txt"
$Count = ($Unique | Measure-Object).Count
$Total = ($Data | Measure-Object).Count
Write-Output "[Info] $Count IP addresses found ($Total)"
# IPv4
# https://ipinfo.io/bogon
$IPv4 = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
$Private = "^(192\.168|10\.|172\.1[6789]\.|172\.2[0-9]\.|172\.3[01]\.)"
$Special = "^(0\.0\.0\.0|127\.0\.0\.1|169\.254\.|224\.0\.0)"
Get-Content "$OUTPUT_FOLDER\FromIP\IP-All.txt" | Select-String -Pattern $IPv4 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique -Property { [System.Version]$_ } | Out-File "$OUTPUT_FOLDER\FromIP\IPv4-All.txt"
Get-Content "$OUTPUT_FOLDER\FromIP\IP-All.txt" | Select-String -Pattern $IPv4 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique -Property { [System.Version]$_ } | Where-Object {$_ -notmatch $Private} | Where-Object {$_ -notmatch $Special} | Out-File "$OUTPUT_FOLDER\FromIP\IPv4.txt"
# Count
$Total = (Get-Content "$OUTPUT_FOLDER\FromIP\IPv4-All.txt" | Measure-Object).Count # Public (Unique) + Private (Unique) --> Note: Extracts IPv4 addresses of IPv4-compatible IPv6 addresses.
$Public = (Get-Content "$OUTPUT_FOLDER\FromIP\IPv4.txt" | Measure-Object).Count # Public (Unique)
Write-Output "[Info] $Public Public IPv4 addresses found ($Total)"
# IPv6
# https://ipinfo.io/bogon
$IPv6 = ":(?::[a-f\d]{1,4}){0,5}(?:(?::[a-f\d]{1,4}){1,2}|:(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})))|[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}|:)|(?::(?:[a-f\d]{1,4})?|(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))))|:(?:(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|[a-f\d]{1,4}(?::[a-f\d]{1,4})?|))|(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|:[a-f\d]{1,4}(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[a-f\d]{1,4}){0,2})|:))|(?:(?::[a-f\d]{1,4}){0,2}(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[a-f\d]{1,4}){1,2})|:))|(?:(?::[a-f\d]{1,4}){0,3}(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[a-f\d]{1,4}){1,2})|:))|(?:(?::[a-f\d]{1,4}){0,4}(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[a-f\d]{1,4}){1,2})|:))"
$Bogon = "^(::1|::ffff:|100::|2001:10::|2001:db8::|fc00::|fe80::|fec0::|ff00::)"
Get-Content "$OUTPUT_FOLDER\FromIP\IP-All.txt" | Select-String -Pattern $IPv6 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique | Out-File "$OUTPUT_FOLDER\FromIP\IPv6-All.txt"
Get-Content "$OUTPUT_FOLDER\FromIP\IP-All.txt" | ForEach-Object{($_ -split "\s+")[5]} | Select-String -Pattern $IPv6 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique | Where-Object {$_ -notmatch $Bogon} | Out-File "$OUTPUT_FOLDER\FromIP\IPv6.txt"
# Count
$Total = (Get-Content "$OUTPUT_FOLDER\FromIP\IPv6-All.txt" | Measure-Object).Count # including Bogus IPv6 addresses (e.g. IPv4-compatible IPv6 addresses)
$Public = (Get-Content "$OUTPUT_FOLDER\FromIP\IPv6.txt" | Measure-Object).Count
Write-Output "[Info] $Public Public IPv6 addresses found ($Total)"
# IP.txt
Write-Output "IPAddress" | Out-File "$OUTPUT_FOLDER\FromIP\IP.txt" # Header
# IPv4.txt
if (Test-Path "$OUTPUT_FOLDER\FromIP\IPv4.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\FromIP\IPv4.txt").Length -gt 0kb)
{
Get-Content -Path "$OUTPUT_FOLDER\FromIP\IPv4.txt" | Out-File "$OUTPUT_FOLDER\FromIP\IP.txt" -Append
}
}
# IPv6.txt
if (Test-Path "$OUTPUT_FOLDER\FromIP\IPv6.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\FromIP\IPv6.txt").Length -gt 0kb)
{
Get-Content -Path "$OUTPUT_FOLDER\FromIP\IPv6.txt" | Out-File "$OUTPUT_FOLDER\FromIP\IP.txt" -Append
}
}
# IP (Inbound)
New-Item "$OUTPUT_FOLDER\FromIP\Inbound" -ItemType Directory -Force | Out-Null
$Data = Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.RecipientAddress -eq "$UserId" } | Select-Object -ExpandProperty FromIP | Where-Object { $_.Trim() -ne "" }
$Unique = $Data | Sort-Object -Unique
$Unique | Out-File "$OUTPUT_FOLDER\FromIP\Inbound\IP-All.txt"
# IPv4 (Inbound)
Get-Content "$OUTPUT_FOLDER\FromIP\Inbound\IP-All.txt" | Select-String -Pattern $IPv4 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique -Property { [System.Version]$_ } | Out-File "$OUTPUT_FOLDER\FromIP\Inbound\IPv4-All.txt"
Get-Content "$OUTPUT_FOLDER\FromIP\Inbound\IP-All.txt" | Select-String -Pattern $IPv4 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique -Property { [System.Version]$_ } | Where-Object {$_ -notmatch $Private} | Where-Object {$_ -notmatch $Special} | Out-File "$OUTPUT_FOLDER\FromIP\Inbound\IPv4.txt"
# IPv6 (Inbound)
Get-Content "$OUTPUT_FOLDER\FromIP\Inbound\IP-All.txt" | Select-String -Pattern $IPv6 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique | Out-File "$OUTPUT_FOLDER\FromIP\Inbound\IPv6-All.txt"
Get-Content "$OUTPUT_FOLDER\FromIP\Inbound\IP-All.txt" | ForEach-Object{($_ -split "\s+")[5]} | Select-String -Pattern $IPv6 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique | Where-Object {$_ -notmatch $Bogon} | Out-File "$OUTPUT_FOLDER\FromIP\Inbound\IPv6.txt"
# IP-Inbound.txt
Write-Output "IPAddress" | Out-File "$OUTPUT_FOLDER\FromIP\Inbound\IP.txt" # Header
# IPv4.txt
if (Test-Path "$OUTPUT_FOLDER\FromIP\Inbound\IPv4.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\FromIP\Inbound\IPv4.txt").Length -gt 0kb)
{
Get-Content -Path "$OUTPUT_FOLDER\FromIP\Inbound\IPv4.txt" | Out-File "$OUTPUT_FOLDER\FromIP\Inbound\IP.txt" -Append
}
}
# IPv6.txt
if (Test-Path "$OUTPUT_FOLDER\FromIP\Inbound\IPv6.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\FromIP\Inbound\IPv6.txt").Length -gt 0kb)
{
Get-Content -Path "$OUTPUT_FOLDER\FromIP\Inbound\IPv6.txt" | Out-File "$OUTPUT_FOLDER\FromIP\Inbound\IP.txt" -Append
}
}
# IP (Outbound)
New-Item "$OUTPUT_FOLDER\FromIP\Outbound" -ItemType Directory -Force | Out-Null
$Data = Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object {$_.SenderAddress -eq "$UserId" } | Select-Object -ExpandProperty FromIP | Where-Object { $_.Trim() -ne "" }
$Unique = $Data | Sort-Object -Unique
$Unique | Out-File "$OUTPUT_FOLDER\FromIP\Outbound\IP-All.txt"
# IPv4 (Outbound)
Get-Content "$OUTPUT_FOLDER\FromIP\Outbound\IP-All.txt" | Select-String -Pattern $IPv4 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique -Property { [System.Version]$_ } | Out-File "$OUTPUT_FOLDER\FromIP\Outbound\IPv4-All.txt"
Get-Content "$OUTPUT_FOLDER\FromIP\Outbound\IP-All.txt" | Select-String -Pattern $IPv4 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique -Property { [System.Version]$_ } | Where-Object {$_ -notmatch $Private} | Where-Object {$_ -notmatch $Special} | Out-File "$OUTPUT_FOLDER\FromIP\Outbound\IPv4.txt"
# IPv6 (Outbound)
Get-Content "$OUTPUT_FOLDER\FromIP\Outbound\IP-All.txt" | Select-String -Pattern $IPv6 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique | Out-File "$OUTPUT_FOLDER\FromIP\Outbound\IPv6-All.txt"
Get-Content "$OUTPUT_FOLDER\FromIP\Outbound\IP-All.txt" | ForEach-Object{($_ -split "\s+")[5]} | Select-String -Pattern $IPv6 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique | Where-Object {$_ -notmatch $Bogon} | Out-File "$OUTPUT_FOLDER\FromIP\Outbound\IPv6.txt"
# IP-Outbound.txt
Write-Output "IPAddress" | Out-File "$OUTPUT_FOLDER\FromIP\Outbound\IP.txt" # Header
# IPv4.txt
if (Test-Path "$OUTPUT_FOLDER\FromIP\Outbound\IPv4.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\FromIP\Outbound\IPv4.txt").Length -gt 0kb)
{
Get-Content -Path "$OUTPUT_FOLDER\FromIP\Outbound\IPv4.txt" | Out-File "$OUTPUT_FOLDER\FromIP\Outbound\IP.txt" -Append
}
}
# IPv6.txt
if (Test-Path "$OUTPUT_FOLDER\FromIP\Outbound\IPv6.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\FromIP\Outbound\IPv6.txt").Length -gt 0kb)
{
Get-Content -Path "$OUTPUT_FOLDER\FromIP\Outbound\IPv6.txt" | Out-File "$OUTPUT_FOLDER\FromIP\Outbound\IP.txt" -Append
}
}
# Check IPinfo Subscription Plan (https://ipinfo.io/pricing)
if (Test-Path "$($IPinfo)")
{
Write-Output "[Info] Checking IPinfo Subscription Plan ..."
[int]$TotalRequests = & $IPinfo quota | Select-String -Pattern "Total Requests" | ForEach-Object{($_ -split "\s+")[-1]}
[int]$RemainingRequests = & $IPinfo quota | Select-String -Pattern "Remaining Requests" | ForEach-Object{($_ -split "\s+")[-1]}
$TotalMonth = '{0:N0}' -f $TotalRequests | ForEach-Object {$_ -replace ' ','.'}
$RemainingMonth = '{0:N0}' -f $RemainingRequests | ForEach-Object {$_ -replace ' ','.'}
if ($TotalRequests -eq "50000") {Write-Output "[Info] IPinfo Subscription: Free ($TotalMonth Requests/Month)`n[Info] $RemainingMonth Requests left this month"} # No Privacy Detection
elseif ($TotalRequests -eq "150000"){Write-Output "[Info] IPinfo Subscription: Basic"} # No Privacy Detection
elseif ($TotalRequests -eq "250000"){Write-Output "[Info] IPinfo Subscription: Standard"} # Privacy Detection
elseif ($TotalRequests -eq "500000"){Write-Output "[Info] IPinfo Subscription: Business"} # Privacy Detection
else {Write-Output "[Info] IPinfo Subscription Plan: Enterprise"} # Privacy Detection
}
# IPinfo CLI
if (Test-Path "$($IPinfo)")
{
if (Test-Path "$OUTPUT_FOLDER\FromIP\IP.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\FromIP\IP.txt").Length -gt 0kb)
{
# Internet Connectivity Check (Vista+)
$NetworkListManager = [Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]‘{DCB00C01-570F-4A9B-8D69-199FDBA5723B}’)).IsConnectedToInternet
if (!($NetworkListManager -eq "True"))
{
Write-Host "[Error] Your computer is NOT connected to the Internet. IP addresses cannot be checked via IPinfo API." -ForegroundColor Red
}
else
{
# Check if IPinfo.io is reachable
if (!(Test-NetConnection -ComputerName ipinfo.io -Port 443).TcpTestSucceeded)
{
Write-Host "[Error] ipinfo.io is NOT reachable. IP addresses cannot be checked via IPinfo API." -ForegroundColor Red
}
else
{
# Map IPs
# https://ipinfo.io/map
New-Item "$OUTPUT_FOLDER\FromIP\IPinfo" -ItemType Directory -Force | Out-Null
# All
Get-Content "$OUTPUT_FOLDER\FromIP\IP.txt" | & $IPinfo map | Out-File "$OUTPUT_FOLDER\FromIP\IPinfo\Map-All.txt"
# Inbound
Get-Content "$OUTPUT_FOLDER\FromIP\Inbound\IP.txt" | & $IPinfo map | Out-File "$OUTPUT_FOLDER\FromIP\IPinfo\Map-Inbound.txt"
# Outbound
Get-Content "$OUTPUT_FOLDER\FromIP\Outbound\IP.txt" | & $IPinfo map | Out-File "$OUTPUT_FOLDER\FromIP\IPinfo\Map-Outbound.txt"
# Access Token
# https://ipinfo.io/signup?ref=cli
if (!("$Token" -eq "access_token"))
{
# Summarize IPs
# https://ipinfo.io/summarize-ips
# TXT (lists VPNs)
Get-Content -Path "$OUTPUT_FOLDER\FromIP\IP.txt" | & $IPinfo summarize -t $Token | Out-File "$OUTPUT_FOLDER\FromIP\IPinfo\Summary.txt"
# CSV --> No Privacy Detection --> Standard ($249/month w/ 250k lookups)
Get-Content -Path "$OUTPUT_FOLDER\FromIP\IP.txt" | & $IPinfo --csv -t $Token | Out-File "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo.csv"
# Custom CSV (Free)
if (Test-Path "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo.csv")
{
if([int](& $xsv count "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo.csv") -gt 0)
{
$Import = Import-Csv "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo.csv" -Delimiter ","
$Import | Foreach-Object {
New-Object -TypeName PSObject -Property @{
"IP" = $_ | Select-Object -ExpandProperty ip
"City" = $_ | Select-Object -ExpandProperty city
"Region" = $_ | Select-Object -ExpandProperty region
"Country" = $_ | Select-Object -ExpandProperty country
"Country Name" = $_ | Select-Object -ExpandProperty country_name
"EU" = $_ | Select-Object -ExpandProperty isEU
"Location" = $_ | Select-Object -ExpandProperty loc
"ASN" = $_ | Select-Object -ExpandProperty org | ForEach-Object{($_ -split "\s+")[0]}
"OrgName" = $_ | Select-Object -ExpandProperty org | ForEach-Object { $_ -replace "^AS[0-9]+ " } # OrgName
"Postal Code" = $_ | Select-Object -ExpandProperty postal
"Timezone" = $_ | Select-Object -ExpandProperty timezone
}
} | Select-Object "IP","City","Region","Country","Country Name","EU","Location","ASN","OrgName","Postal Code","Timezone" | Sort-Object {$_.ip -as [Version]} | ConvertTo-Csv -NoTypeInformation -Delimiter "," | Out-File "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo-Custom.csv"
}
}
# Custom XLSX (Free)
if (Test-Path "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo-Custom.csv")
{
if([int](& $xsv count "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo-Custom.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo-Custom.csv" -Delimiter "," | Sort-Object {$_.ip -as [Version]}
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo-Custom.xlsx" -NoNumberConversion * -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -IncludePivotTable -PivotTableName "PivotTable" -PivotRows "Country Name" -PivotData @{"IP"="Count"} -WorkSheetname "IPinfo (Free)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:K1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-K
$WorkSheet.Cells["A:K"].Style.HorizontalAlignment="Center"
}
}
}
# Count
if (Test-Path "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo-Custom.csv")
{
if([int](& $xsv count "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo-Custom.csv") -gt 0)
{
# Suspicious ASN (Autonomous System Number)
$Data = Import-Csv -Path "$OUTPUT_FOLDER\FromIP\IPinfo\IPinfo-Custom.csv" -Delimiter ","
$Total = ($Data | Select-Object ASN | Measure-Object).Count
$Count = ($Data | Select-Object ASN -Unique | Measure-Object).Count