解决方法:
# 设置AD账户的过期时间为90天
$expiryDate = (Get-Date).AddDays(90)
# 获取所有AD用户
$users = Get-ADUser -Filter * -Properties AccountExpirationDate
# 遍历每个用户检查过期时间
foreach ($user in $users) {
# 检查过期时间是否为空
if ($user.AccountExpirationDate -eq $null) {
# 设置过期时间为90天后
Set-ADUser -Identity $user -AccountExpirationDate $expiryDate
Write-Host "已设置账户 $($user.Name) 过期时间为 $expiryDate"
}
}
# 发送邮件通知
$smtpServer = "smtp.example.com"
$smtpPort = 587
$smtpUsername = "your-email@example.com"
$smtpPassword = "your-password"
$sender = "your-email@example.com"
$recipients = "recipient1@example.com", "recipient2@example.com"
$subject = "AD账户过期提醒"
$body = "您的AD账户将在 $expiryDate 过期,请及时更新密码。"
# 创建SMTP客户端
$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort)
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = New-Object System.Net.NetworkCredential($smtpUsername, $smtpPassword)
# 创建邮件消息
$mailMessage = New-Object System.Net.Mail.MailMessage
$mailMessage.From = $sender
$mailMessage.Subject = $subject
$mailMessage.Body = $body
# 添加收件人
foreach ($recipient in $recipients) {
$mailMessage.To.Add($recipient)
}
# 发送邮件
$smtpClient.Send($mailMessage)
将以上代码保存为一个后缀为 .ps1
的 PowerShell 脚本文件,比如 expiry_notification.ps1
。
打开 PowerShell 终端,通过以下命令执行脚本:
.\expiry_notification.ps1
注意:在执行脚本之前,需要在计算机上安装 Active Directory PowerShell 模块。可以通过运行 Import-Module ActiveDirectory
命令导入该模块。