D0cEvil

O365 - Export Office 365 Spam and Malware Report

Sep 23rd, 2022
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 7.51 KB | Cybersecurity | 0 0
  1. <#
  2. =============================================================================================
  3. Name:           Export Office 365 Spam and Malware Report using PowerShell
  4. Description:    This script exports Office 365 spam and malware report  to CSV
  5. Version:        1.0
  6. Website:        o365reports.com
  7. Script by:      O365Reports Team
  8. For detailed script execution: https://o365reports.com/2021/05/18/export-office-365-spam-and-malware-report-using-powershell
  9. ============================================================================================
  10. #>
  11.  
  12. param(
  13.     [string] $UserName = $null,
  14.     [string] $Password = $null,
  15.     [Switch] $SpamEmailsSent,
  16.     [Switch] $SpamEmailsReceived,
  17.     [Switch] $MalwareEmailsSent,
  18.     [Switch] $MalwareEmailsReceived,
  19.     [Nullable[DateTime]]$StartDate,
  20.     [Nullable[DateTime]]$EndDate
  21. )
  22.  
  23. Function DateAndSwitchesValidation {
  24.     $global:MaxStartDate = ((Get-Date).Date).AddDays(-10)
  25.     if (($StartDate -eq $Null) -and ($EndDate -eq $Null)) {
  26.         $StartDate = $global:MaxStartDate
  27.         $EndDate = (Get-date).Date
  28.     }
  29.     elseif (($StartDate -eq $null) -or ($EndDate -eq $null)) {
  30.             Write-Host "Exiting.`nNote: Both start and end date values are mandatory. Please try again." -ForegroundColor Red
  31.             Exit
  32.         }
  33.     elseif ($StartDate -lt $global:MaxStartDate) {
  34.             Write-Host "Exiting.`nNote: You can retrieve data from $global:MaxStartDate onwards. Please try again." -ForegroundColor Red
  35.             Exit
  36.         }
  37.     else {
  38.          $StartDate = [DateTime]$StartDate
  39.          $EndDate = [DateTime]$EndDate
  40.         }
  41.     if(-Not(($SpamEmailsSent.IsPresent)-or($SpamEmailsReceived.IsPresent)-or($MalwareEmailsSent.IsPresent)-or($MalwareEmailsReceived.IsPresent))){
  42.         Write-Host "Exiting.`nNote: Choose one report to generate. Please try again" -ForegroundColor Red
  43.         Exit
  44.     }
  45.     GetSpamMalwareData -StartDate $StartDate -EndDate $EndDate
  46. }
  47. Function GetSpamMalwareData {
  48.     param (
  49.         [DateTime]$StartDate,
  50.         [DateTime]$EndDate
  51.     )
  52.  
  53.     $EndDate = Get-Date $EndDate -Hour 23 -Minute 59 -Second 59
  54.    
  55.     ConnectToExchange
  56.     $global:ExportedEmails = 0
  57.     $global:Domain = "Recipient Domain"
  58.  
  59.     if ($SpamEmailsReceived.IsPresent) {
  60.         $global:ExportCSVFileName = ".\SpamEmailsReceivedReport-" + ((Get-Date -format "MMM-dd hh-mm-ss tt").ToString()) + ".csv"
  61.         Write-Host "Retrieving spam emails received from $StartDate to $EndDate..."
  62.         Get-MailDetailSpamReport -StartDate $StartDate -EndDate $EndDate -Direction Inbound -PageSize 5000 | ForEach-Object {
  63.             $global:Domain = "Sender Domain"
  64.             $CurrRecord = $_
  65.             RetrieveEmailInfo
  66.         }  
  67.     }
  68.     elseif ($MalwareEmailsReceived.IsPresent) {
  69.         $global:ExportCSVFileName = ".\MalwareEmailsReceivedReport-" + ((Get-Date -format "MMM-dd hh-mm-ss tt").ToString()) + ".csv"
  70.         Write-Host "Retrieving malware emails received from $StartDate to $EndDate..."
  71.         Get-MailDetailMalwareReport -StartDate $StartDate -EndDate $EndDate -Direction Inbound -PageSize 5000 | ForEach-Object {
  72.             $global:Domain = "Sender Domain"
  73.             $CurrRecord = $_
  74.             RetrieveEmailInfo
  75.         }  
  76.     }
  77.     elseif ($SpamEmailsSent.IsPresent) {
  78.         $global:ExportCSVFileName = ".\SpamEmailsSentReport-" + ((Get-Date -format "MMM-dd hh-mm-ss tt").ToString()) + ".csv"
  79.         Write-Host "Retrieving spam emails sent from $StartDate to $EndDate..."
  80.         Get-MailDetailSpamReport -StartDate $StartDate -EndDate $EndDate -Direction Outbound -PageSize 5000 | ForEach-Object {
  81.             $CurrRecord = $_
  82.             RetrieveEmailInfo
  83.         }  
  84.     }
  85.     elseif ($MalwareEmailsSent.IsPresent) {
  86.         $global:ExportCSVFileName = ".\MalwareEmailsSentReport-" + ((Get-Date -format "MMM-dd hh-mm-ss tt").ToString()) + ".csv"
  87.         Write-Host "Retrieving malware emails sent from $StartDate to $EndDate..."
  88.         Get-MailDetailMalwareReport -StartDate $StartDate -EndDate $EndDate -Direction Outbound -PageSize 5000 | ForEach-Object {
  89.             $CurrRecord = $_
  90.             RetrieveEmailInfo
  91.         }  
  92.     }
  93. }
  94. Function ConnectToExchange {
  95.     $Exchange = (get-module ExchangeOnlineManagement -ListAvailable).Name
  96.     if ($Exchange -eq $null) {
  97.         Write-host "Important: ExchangeOnline PowerShell module is unavailable. It is mandatory to have this module installed in the system to run the script successfully."
  98.         $confirm = Read-Host Are you sure you want to install module? [Y] Yes [N] No  
  99.         if ($confirm -match "[yY]") {
  100.             Write-host "Installing ExchangeOnlineManagement"
  101.             Install-Module ExchangeOnlineManagement -Repository PSGallery -AllowClobber -Force
  102.             Write-host "ExchangeOnline PowerShell module is installed in the machine successfully."
  103.         }
  104.         elseif ($confirm -cnotmatch "[yY]" ) {
  105.             Write-host "Exiting. `nNote: ExchangeOnline PowerShell module must be available in your system to run the script."
  106.             Exit
  107.         }
  108.     }
  109.     #Storing credential in script for scheduling purpose/Passing credential as parameter
  110.     if (($UserName -ne "") -and ($Password -ne "")) {  
  111.         $SecuredPassword = ConvertTo-SecureString -AsPlainText $Password -Force  
  112.         $Credential = New-Object System.Management.Automation.PSCredential $UserName, $SecuredPassword
  113.         Connect-ExchangeOnline -Credential $Credential -ShowProgress $false | Out-Null
  114.     }
  115.     else {
  116.         Connect-ExchangeOnline | Out-Null
  117.     }
  118.     Write-Host "ExchangeOnline PowerShell module is connected successfully"
  119.     #End of Connecting Exchange Online
  120. }
  121. Function RetrieveEmailInfo {
  122.     $Date = $CurrRecord.Date.ToShortDateString()
  123.     $DateTime = $CurrRecord.Date
  124.     Write-Progress -Activity "Retrieving mail data for $Date"
  125.     $SenderAddress = $CurrRecord.SenderAddress
  126.     $RecipientAddress = $CurrRecord.RecipientAddress
  127.     $Subject = $CurrRecord.Subject
  128.     $EventType = $CurrRecord.EventType
  129.     if($CurrRecord.Direction -eq 'Inbound'){
  130.         $Domain = $SenderAddress.split("@") | Select-object -Index 1
  131.     }
  132.     else{
  133.         $Domain = $RecipientAddress.split("@") | Select-object -Index 1
  134.     }
  135.     ExportResults
  136. }
  137. Function ExportResults {
  138.     $global:ExportedEmails = $global:ExportedEmails + 1
  139.     $ExportResult = @{'Date' = $DateTime; 'Sender Address' = $SenderAddress; 'Recipient Address' = $RecipientAddress; 'Subject'= $Subject; 'Event Type' = $EventType; $global:Domain = $Domain}
  140.     $ExportResults = New-Object PSObject -Property $ExportResult
  141.     $ExportResults | Select-Object 'Date', 'Sender Address', 'Recipient Address', 'Subject', 'Event Type',$global:Domain | Export-csv -path $global:ExportCSVFileName -NoType -Append -Force  
  142. }
  143.  
  144. DateAndSwitchesValidation
  145.  
  146.  
  147. #Open output file after execution
  148. if ((Test-Path -Path $global:ExportCSVFileName) -eq "True") {
  149.     Write-Host "The output file available in $global:ExportCSVFileName" -ForegroundColor Green
  150.     Write-Host "The exported report has $global:ExportedEmails email details"
  151.     $prompt = New-Object -ComObject wscript.shell    
  152.     $userInput = $prompt.popup("Do you want to open output file?", 0, "Open Output File", 4)    
  153.     If ($userInput -eq 6) {    
  154.         Invoke-Item "$global:ExportCSVFileName"
  155.     }  
  156. }
  157. else {
  158.     Write-Host "No data found with the specified criteria"
  159. }
  160. Disconnect-ExchangeOnline -Confirm:$false -InformationAction Ignore -ErrorAction SilentlyContinue
  161. Write-Host "Disconnected active ExchangeOnline session"
Add Comment
Please, Sign In to add comment