首页
/ PowerShell项目实战:基于Graph API实现Teams密码到期提醒系统

PowerShell项目实战:基于Graph API实现Teams密码到期提醒系统

2025-06-04 10:03:13作者:农烁颖Land

前言

在企业IT运维中,密码策略管理是基础但重要的工作。传统通过邮件发送密码到期提醒的方式存在诸多不足,而利用Microsoft Teams即时通讯工具配合Graph API可以实现更高效的提醒机制。本文将详细介绍如何使用PowerShell结合Graph API构建一个自动化密码到期提醒系统。

技术背景

Microsoft Graph API简介

Microsoft Graph API是微软提供的统一API接口,它整合了多个微软云服务的访问端点。通过Graph API,开发者可以使用单一接口访问包括Azure AD、Teams、OneDrive等在内的多种服务数据。

与传统API相比,Graph API具有以下优势:

  • 统一的认证授权机制
  • 标准化的数据模型
  • 跨服务的关联查询能力
  • 支持多种认证方式(令牌、证书等)

相关技术组件

  1. Microsoft.Graph PowerShell模块:微软官方提供的用于与Graph API交互的PowerShell模块
  2. Teams聊天API:Graph API中用于管理Teams聊天的接口
  3. Active Directory模块:用于获取本地AD用户密码策略信息

环境准备

1. 安装必要模块

# 安装Microsoft Graph PowerShell模块
Install-Module -Name Microsoft.Graph -Force -AllowClobber

# 导入Active Directory模块(已内置在Windows Server中)
Import-Module ActiveDirectory

2. 配置API权限

Graph API采用基于权限范围(Scope)的访问控制模型。我们需要预先声明脚本所需的权限:

$RequiredScopes = @(
    'Chat.Create'       # 创建聊天会话
    'Chat.ReadWrite'    # 读写聊天消息
    'User.Read'         # 读取用户基本信息
    'User.Read.All'     # 读取所有用户信息
)

核心实现步骤

1. 连接Graph API

Connect-MgGraph -Scopes $RequiredScopes

连接后可通过Get-MgContext查看当前连接上下文信息。

2. 获取密码即将到期的用户

# 设置提醒阈值(7天)
$WarningDays = 7
$ExpiryDate = (Get-Date).AddDays($WarningDays).Date

# 查询AD中密码即将过期的用户
$Users = Get-ADUser -Filter {
    Enabled -eq $true -and
    PasswordNeverExpires -eq $false -and
    PasswordLastSet -gt 0
} -Properties msDS-UserPasswordExpiryTimeComputed, Mail, DisplayName |
Where-Object {
    [datetime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed').Date -eq $ExpiryDate
}

3. 创建Teams聊天会话

对于每个需要提醒的用户,我们需要先建立聊天会话:

$ChatParams = @{
    ChatType = "oneOnOne"
    Members = @(
        @{
            "@odata.type" = "#microsoft.graph.aadUserConversationMember"
            Roles = @("owner")
            "User@odata.bind" = "https://graph.microsoft.com/v1.0/users('$SenderID')"
        }
        @{
            "@odata.type" = "#microsoft.graph.aadUserConversationMember"
            Roles = @("owner")
            "User@odata.bind" = "https://graph.microsoft.com/v1.0/users('$RecipientID')"
        }
    )
}

$Chat = New-MgChat -BodyParameter $ChatParams

4. 发送提醒消息

$MessageBody = @{
    ContentType = 'html'
    Content = @"
    <div style='font-family: Segoe UI, sans-serif'>
        <h3 style='color: #2564CF'>密码到期提醒</h3>
        <p>尊敬的 $($User.DisplayName):</p>
        <p>您的密码将在 <strong>$WarningDays 天</strong> 后过期(到期时间: $ExpiryDate)。</p>
        <p>请及时<a href='https://passwordreset.microsoftonline.com' style='color: #2564CF; text-decoration: none'>修改密码</a>。</p>
        <p style='color: #797775; font-size: 0.8em'>此为自动发送的消息,请勿直接回复。</p>
    </div>
"@
}

New-MgChatMessage -ChatId $Chat.Id -Body $MessageBody

完整脚本实现

将上述步骤整合,形成完整的自动化脚本:

<#
.SYNOPSIS
    通过Teams发送AD用户密码到期提醒
.DESCRIPTION
    该脚本查询AD中密码即将过期的用户,并通过Teams发送提醒消息。
    需要提前配置好Microsoft Graph API权限。
#>

# 初始化环境
Import-Module Microsoft.Graph.Teams
Import-Module ActiveDirectory

# 配置Graph API权限范围
$RequiredScopes = @('Chat.Create','Chat.ReadWrite','User.Read','User.Read.All')
Connect-MgGraph -Scopes $RequiredScopes

# 配置参数
$WarningDays = 7  # 提前提醒天数
$ExpiryDate = (Get-Date).AddDays($WarningDays).Date
$SenderID = (Get-MgUser -UserId (Get-MgContext).Account).Id

# 获取密码即将过期的用户
$ExpiringUsers = Get-ADUser -Filter {
    Enabled -eq $true -and
    PasswordNeverExpires -eq $false -and
    PasswordLastSet -gt 0
} -Properties msDS-UserPasswordExpiryTimeComputed, Mail, DisplayName |
Where-Object {
    [datetime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed').Date -eq $ExpiryDate
}

# 处理每个需要提醒的用户
foreach ($User in $ExpiringUsers) {
    try {
        # 获取接收者Graph ID
        $Recipient = Get-MgUser -UserId $User.Mail -ErrorAction Stop
        
        # 创建或获取聊天会话
        $ChatParams = @{
            ChatType = "oneOnOne"
            Members = @(
                @{
                    "@odata.type" = "#microsoft.graph.aadUserConversationMember"
                    Roles = @("owner")
                    "User@odata.bind" = "https://graph.microsoft.com/v1.0/users('$SenderID')"
                }
                @{
                    "@odata.type" = "#microsoft.graph.aadUserConversationMember"
                    Roles = @("owner")
                    "User@odata.bind" = "https://graph.microsoft.com/v1.0/users('$($Recipient.Id)')"
                }
            )
        }
        $Chat = New-MgChat -BodyParameter $ChatParams

        # 构建并发送消息
        $MessageBody = @{
            ContentType = 'html'
            Content = @"
            <div style='font-family: Segoe UI, sans-serif'>
                <h3 style='color: #2564CF'>密码到期提醒</h3>
                <p>尊敬的 $($User.DisplayName):</p>
                <p>您的密码将在 <strong>$WarningDays 天</strong> 后过期(到期时间: $ExpiryDate)。</p>
                <p>请及时<a href='https://passwordreset.microsoftonline.com' style='color: #2564CF; text-decoration: none'>修改密码</a>。</p>
                <p style='color: #797775; font-size: 0.8em'>此为自动发送的消息,请勿直接回复。</p>
            </div>
"@
        }
        New-MgChatMessage -ChatId $Chat.Id -Body $MessageBody
        
        Write-Host "已向 $($User.Mail) 发送提醒" -ForegroundColor Green
    }
    catch {
        Write-Warning "向 $($User.Mail) 发送提醒失败: $_"
    }
}

# 断开Graph连接
Disconnect-MgGraph

进阶优化建议

  1. 消息模板定制:可以将消息内容存储在外部HTML模板文件中,实现灵活配置

  2. 多语言支持:根据用户区域设置发送对应语言的提醒

  3. 发送记录追踪:将发送记录写入日志或数据库,避免重复提醒

  4. 异常处理增强:添加重试机制和更完善的错误处理

  5. 计划任务集成:通过Windows计划任务定期执行脚本

常见问题排查

  1. 权限不足错误

    • 检查Connect-MgGraph时指定的Scope是否完整
    • 确保管理员已在Azure AD中授予了同意
  2. 用户查找失败

    • 确认AD用户的mail属性已正确同步到Azure AD
    • 检查用户是否已启用Teams
  3. 消息发送失败

    • 验证聊天会话是否创建成功
    • 检查消息内容是否符合HTML格式要求

结语

本文介绍了利用PowerShell和Graph API实现Teams密码到期提醒的完整方案。这种方案相比传统邮件提醒具有以下优势:

  • 更高的消息到达率和可见性
  • 更友好的用户交互体验
  • 与企业现有Teams环境无缝集成
  • 可扩展性强,易于添加更多自动化功能

读者可以根据实际需求调整脚本,如添加二次提醒、集成自助密码重置等功能,构建更完善的密码管理解决方案。

登录后查看全文
热门项目推荐