You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过PowerShell脚本拉取Azure AD Connect同步状态报告并邮件发送?

Azure AD Connect同步连接器状态自动报告方案

一、PowerShell脚本实现

以下脚本可拉取所有连接器的近期同步操作状态,并通过服务账号自动发送邮件报告:

# 加载ADSync模块(Azure AD Connect默认自带)
Import-Module ADSync

# 获取所有同步连接器
$connectors = Get-ADSyncConnector

# 初始化结果存储数组
$syncStatusResults = @()

foreach ($connector in $connectors) {
    # 筛选指定操作类型的最近一次运行记录
    $latestRun = Get-ADSyncConnectorRunStatus -Connector $connector | 
        Where-Object RunType -in 'FullSynchronization', 'FullImport', 'DeltaSynchronization' |
        Sort-Object StartTime -Descending |
        Select-Object RunType, StartTime, EndTime, Status, ErrorCount -First 1

    # 整理结果对象
    $result = [PSCustomObject]@{
        连接器名称 = $connector.Name
        操作类型   = $latestRun.RunType ?? '无近期记录'
        开始时间   = $latestRun.StartTime.ToString('yyyy-MM-dd HH:mm:ss') ?? '-'
        结束时间   = if ($latestRun.EndTime) { $latestRun.EndTime.ToString('yyyy-MM-dd HH:mm:ss') } else { '运行中' }
        状态       = $latestRun.Status ?? '-'
        错误数     = $latestRun.ErrorCount ?? '-'
    }
    $syncStatusResults += $result
}

# 生成HTML格式的邮件内容
$htmlBody = @"
<h2>Azure AD Connect同步连接器状态报告</h2>
<p>报告生成时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')</p>
$( $syncStatusResults | ConvertTo-Html -Fragment )
"@

# 邮件配置参数,请根据实际环境修改
$smtpServer   = 'smtp.yourcompany.com'
$smtpPort     = 587
$fromAddress  = 'sync-report-service@yourcompany.com'
$toAddresses  = @('it-admin@yourcompany.com', 'sync-team@yourcompany.com')
$emailSubject = "Azure AD Connect同步状态报告 - $(Get-Date -Format 'yyyy-MM-dd')"

# 加载加密存储的服务账号凭据(提前执行一次导出命令:$cred | Export-Clixml -Path 'C:\Scripts\SyncReportCred.xml')
$credential = Import-Clixml -Path 'C:\Scripts\SyncReportCred.xml'

# 发送邮件
Send-MailMessage -SmtpServer $smtpServer -Port $smtpPort `
    -From $fromAddress -To $toAddresses `
    -Subject $emailSubject -Body $htmlBody -BodyAsHtml `
    -UseSsl -Credential $credential

二、关键配置说明

  • 模块验证:在Azure AD Connect服务器上执行Get-Module ADSync确认模块已安装
  • 凭据加密存储:首次运行时执行Get-Credential | Export-Clixml -Path 'C:\Scripts\SyncReportCred.xml',将服务账号凭据加密存储,避免自动执行时手动输入
  • SMTP参数调整:根据企业邮件服务器配置修改$smtpServer、$smtpPort,若无需SSL可移除-UseSsl参数
  • 操作类型自定义:可修改Where-Object中的RunType值,添加或移除需要监控的同步操作类型

三、自动化部署(Windows任务计划)

  1. 打开任务计划程序 → 创建自定义任务
  2. 触发器:设置每日执行时间(如凌晨1点,避开同步高峰)
  3. 操作:选择“启动程序”,程序路径填powershell.exe,参数填-ExecutionPolicy Bypass -File "C:\Scripts\SyncStatusReport.ps1"
  4. 常规选项卡:勾选“不管用户是否登录都要运行”,指定服务账号为执行账户,确保账户有ADSync模块访问权限和邮件发送权限
  5. 设置:勾选“如果任务失败,重试次数”,确保报告稳定生成

内容的提问来源于stack exchange,提问作者hacrks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:15:59