
Office365 PowerShell打开邮箱审计功能
创建密码安全字符串并存储到临时文件
发布日期:2025-04-27 12:59:42
浏览次数:3
分类:精选文章
本文共 2706 字,大约阅读时间需要 9 分钟。
最近公司要求所有邮箱开启Office365的审计功能。虽然微软提供了官方脚本,但存在一个潜在问题。
当尝试通过PowerShell脚本修改邮箱设置时,发现一个严重的bug。具体表现为,无论输入哪个属性(如displayname、ID等),脚本最终都会使用displayname作为修改目标。这意味着如果存在同名的邮箱,系统可能无法确定具体修改哪个邮箱,导致操作失败。
经过深入分析,发现这是由于Office365允许同名账户存在(如AD同步账户和云创建账户),且displayname相同导致的。
为解决此问题,建议避免使用官方脚本,而改用手动循环处理DistinguishedName等属性。这样可以确保修改时不会因displayname冲突而出错。
此外,Office365默认不开启审计功能,因此需要设置计划任务定期执行脚本。同时,建议在修改后通过邮件通知管理员,并记录操作日志以备查验。
以下是完整的脚本示例:
Read-Host -AsSecureString | ConvertFrom-SecureString > C:\temp\key.txt
- 检查并建立O365会话
- 找出尚未启用的邮箱并启用审计
- 检查结果并发送通知邮件
$Sessions = Get-PSSessionif ((($Sessions.ComputerName -eq "outlook.office365.com") -and ($Sessions.State -ne 'Broken'))) { Write-Host "Detect existing Office365 session, skip." -ForegroundColor Cyan} else { $username = "yuan.li@aus.ddb.com" $secureStringPwd = Get-Credential -File C:\temp\key.txt $creds = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd $ExoSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $creds -Authentication Basic -AllowRedirection Import-PSSession $ExoSession}
$users = Get-Mailbox -Filter { AuditEnabled -eq $false } | Select name, alias, auditenabled, auditlogagelimit, distinguishednameforeach ($user in $users) { try { Set-Mailbox -Identity $user.distinguishedname -AuditEnabled $true -AuditLogAgeLimit 365 -AuditOwner Create,HardDelete,MailboxLogin,MoveToDeletedItems,SoftDelete,Update -ErrorAction Stop $username = $user.name Write-EventLog -Logname 'Application' -Source 'Application' -EventID 666 -EntryType Information -Message "$username Mailbox Auditing is enabled" } catch { Write-EventLog -Logname 'Application' -Source 'Application' -EventID 667 -EntryType Error -Message "$user Mailbox Auditing is failed to enable" }}
$result = foreach ($user in $users) { Get-Mailbox $user.name | Select name, alias, auditenabled, auditlogagelimit, distinguishedname}$from = "yuan.li@syd.ddb.com"$to = "yuan.li@syd.ddb.com"$smtp = "smtp.office365.com"$subject = "Auditing list"$secureStringPwd = Get-Credential -File C:\temp\key.txt$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd$date = Get-Date$htmlbody = $result | ConvertTo-Html -Body "$date Mailbox Auditing Enabled record
" -CssUri C:\tmp\table.cssSend-MailMessage -To $to -From $from -Subject $subject -Body ($htmlbody | Out-String) -Credential $creds -SmtpServer $smtp -DeliveryNotificationOption Never -BodyAsHtml -UseSsl -port 587
测试结果表明,该脚本能够成功启用所有未启用的邮箱审计功能。同时,Windows事件日志和邮件通知可以用来跟踪操作结果。建议在两天后确认状态是否已更改。
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2025年04月06日 02时03分14秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!