Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
Auditing shared mailbox activities is a critical task in Microsoft 365 environments to ensure compliance, monitor user actions, and detect unauthorized access or modifications. Microsoft 365 provides robust audit logging capabilities, which can be leveraged using PowerShell to track activities such as email deletions, access events, and modifications performed by delegated users or administrators.
This article introduces a PowerShell script designed to simplify the process of auditing shared mailbox activities. The script retrieves audit logs, filters specific actions, and exports the results into a CSV file for further analysis.
Shared mailboxes are often used by teams to manage shared email accounts, such as support@domain.com
or info@domain.com
. However, without proper monitoring, these mailboxes can be vulnerable to:
By auditing shared mailbox activities, administrators can:
The script simplifies the auditing process by offering the following features:
1. Retrieve Audit Logs:
2. Track Specific Actions:
SendAs
, SendOnBehalf
, FolderBind
, HardDelete
, SoftDelete
, MoveToDeletedItems
, and more.3. Export Results:
4. Flexible Authentication:
5. Automatic Module Installation:
6. Scheduler-Friendly:
Before running the script, ensure the following:
1. Permissions:
Get-AdminAuditLogConfig
Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true
3. PowerShell Module:
Install-Module ExchangeOnlineManagement -Repository PSGallery -Force
Before running the script, connect to Exchange Online using the following command:
Connect-ExchangeOnline -UserPrincipalName admin@yourdomain.com
For certificate-based authentication, use:
Connect-ExchangeOnline -AppId <ClientId> -CertificateThumbprint <Thumbprint> -Organization <YourDomain>
Save the provided PowerShell script as Audit-SharedMailbox.ps1
and execute it with the following command:
.\Audit-SharedMailbox.ps1 -SharedMailboxUPN "support@yourdomain.com"
This retrieves all activities performed on the shared mailbox support@yourdomain.com
within the last 180 days.
To focus on specific actions, such as email deletions, modify the script to include only relevant operations:
Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) -Operations "HardDelete", "SoftDelete", "MoveToDeletedItems"
This retrieves logs related to email deletions in the past 30 days.
The script automatically exports the results to a CSV file. Alternatively, you can manually export the results using:
Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) -Operations "HardDelete", "SoftDelete", "MoveToDeletedItems" | Export-Csv -Path "C:\AuditResults.csv" -NoTypeInformation
The CSV file includes columns such as:
After completing the audit, disconnect the Exchange Online session:
Disconnect-ExchangeOnline -Confirm:$false
The script is highly customizable to suit your organization's needs:
-StartDate
and -EndDate
parameters.-IncludeExternalAccess
switch to include activities performed by external users.-Organization
, -ClientId
, and -CertificateThumbprint
parameters for unattended execution.1. Enable Audit Logging:
$IntervalTimeInMinutes
variable in the script to optimize performance for large datasets.<#
.SYNOPSIS
Audita atividades em shared mailboxes no Microsoft 365\.
.DESCRIPTION
Este script recupera logs de auditoria para uma shared mailbox específica e exporta os resultados para um arquivo CSV.
.PARAMETER SharedMailboxUPN
O UPN da shared mailbox a ser auditada (ex: suporte@dominio.com).
.PARAMETER StartDate
A data de início para a auditoria (padrão: 180 dias atrás).
.PARAMETER EndDate
A data de término para a auditoria (padrão: data atual).
.PARAMETER OutputPath
O caminho e nome do arquivo CSV de saída.
.PARAMETER IncludeExternalAccess
Inclui atividades realizadas por usuários externos.
.PARAMETER Operations
Filtra as operações a serem auditadas (padrão: SendAs, SendOnBehalf, HardDelete, SoftDelete).
.EXAMPLE
.\Audit-SharedMailbox.ps1 -SharedMailboxUPN "suporte@dominio.com"
.EXAMPLE
.\Audit-SharedMailbox.ps1 -SharedMailboxUPN "suporte@dominio.com" -StartDate "2024-01-01" -EndDate "2024-01-31" -Operations "SendAs", "HardDelete"
#>
Param (
[Parameter(Mandatory = $true)]
[ValidatePattern('^[a-zA-Z0-9\._%+-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,}$')]
[string]$SharedMailboxUPN,
[Nullable[DateTime]]$StartDate,
[Nullable[DateTime]]$EndDate,
[string]$OutputPath = "$PSScriptRoot\Audit_Shared_Mailbox_Activities_$((Get-Date -format yyyy-MMM-dd).ToString()).csv",
[switch]$IncludeExternalAccess,
[string[]]$Operations = @('SendAs', 'SendOnBehalf', 'HardDelete', 'SoftDelete', 'MoveToDeletedItems')
)
# Função para escrever logs
function Write-Log {
Param ([string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $LogFile -Value "[$Timestamp] $Message"
}
# Configuração de logs
$LogFile = "$PSScriptRoot\Audit_Shared_Mailbox_Log_$((Get-Date -format yyyy-MMM-dd).ToString()).log"
Write-Log "Iniciando script de auditoria para a shared mailbox: $SharedMailboxUPN"
# Validação de datas
if (-not $StartDate) { $StartDate = (Get-Date).AddDays(-180) }
if (-not $EndDate) { $EndDate = Get-Date }
if ($StartDate -gt $EndDate) {
Write-Host "A data de início não pode ser maior que a data de término." -ForegroundColor Red
Write-Log "Erro: Data de início maior que data de término."
Exit
}
Write-Log "Período de auditoria: $StartDate até $EndDate"
# Conectar ao Exchange Online
Try {
Write-Log "Conectando ao Exchange Online..."
Connect-ExchangeOnline -UserPrincipalName $env:USERNAME -ShowBanner:$false -ErrorAction Stop
Write-Log "Conexão ao Exchange Online bem-sucedida."
}
Catch {
Write-Host "Falha ao conectar ao Exchange Online: $_" -ForegroundColor Red
Write-Log "Falha ao conectar ao Exchange Online: $_"
Exit
}
# Recuperar logs de auditoria com paginação
$SessionId = [Guid]::NewGuid().ToString()
$Results = @()
$Page = 1
Write-Log "Iniciando recuperação de logs de auditoria..."
do {
Write-Log "Recuperando página $Page..."
$AuditLogs = Search-UnifiedAuditLog -StartDate $StartDate -EndDate $EndDate -SessionId $SessionId -SessionCommand ReturnLargeSet -ResultSize 5000 -Operations $Operations
$Results += $AuditLogs
$Page++
} while ($AuditLogs.Count -eq 5000)
Write-Log "Recuperação de logs concluída. Total de registros: $($Results.Count)"
# Filtrar resultados
$FilteredResults = @()
foreach ($Log in $Results) {
$AuditData = $Log.AuditData | ConvertFrom-Json
# Filtrar acessos externos (se necessário)
if (-not $IncludeExternalAccess -and $AuditData.ExternalAccess -eq $true) {
continue
}
# Filtrar atividades da shared mailbox específica
if ($AuditData.MailboxOwnerUPN -eq $SharedMailboxUPN) {
$FilteredResults += [PSCustomObject]@{
'Activity Time' = (Get-Date $AuditData.CreationTime).ToLocalTime()
'Performed by' = $AuditData.UserId
'Performed Operation' = $AuditData.Operation
'Shared Mailbox Name' = $AuditData.MailboxOwnerUPN
'Logon Type' = if ($AuditData.LogonType -eq 1) { "Administrator" } elseif ($AuditData.LogonType -eq 2) { "Delegated" } else { "Microsoft Datacenter" }
'Result Status' = $AuditData.ResultStatus
'External Access' = $AuditData.ExternalAccess
'More Info' = $Log.AuditData
}
}
}
Write-Log "Filtragem concluída. Total de registros filtrados: $($FilteredResults.Count)"
# Exportar resultados para CSV
Try {
$FilteredResults | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Host "Relatório exportado para: $OutputPath" -ForegroundColor Green
Write-Log "Relatório exportado para: $OutputPath"
}
Catch {
Write-Host "Falha ao exportar o relatório: $_" -ForegroundColor Red
Write-Log "Falha ao exportar o relatório: $_"
}
# Desconectar do Exchange Online
Try {
Write-Log "Desconectando do Exchange Online..."
Disconnect-ExchangeOnline -Confirm:$false
Write-Log "Desconexão bem-sucedida."
}
Catch {
Write-Host "Falha ao desconectar do Exchange Online: $_" -ForegroundColor Red
Write-Log "Falha ao desconectar do Exchange Online: $_"
}
Write-Log "Script concluído."