背景:
公司搭建了AD和Exchange进行配套使用,但是对于邮箱账户密码过期没有一个很好地通知方式。为了解决这个情况,想到获取AD中的即将过期并进行邮件通知。
环境:
Windows Server 2012 R2 、Exchange 2013
Powershell脚本:
############################################
#Author:Young,时间:2017年9月
#Email:Mr_wang_yang@163.com
#For:检测AD密码过期时间并邮件通知
#Version:1.1
##############################################
Import-Module Activedirectory
#@1和@2选择一个执行
#@1检索出指定OU里不包含设置了永不过期及禁用的账户
$alladuser=get-aduser -searchbase "OU=test,DC=bigyoung,DC=cn" -Filter 'PasswordNeverExpires -eq "false" -and enabled -eq "true"' | ForEach{$_.SamAccountName}
#@2检索出所有OU里不包含设置了永不过期及禁用的账户
#$alladuser=Get-ADUser -Filter 'PasswordNeverExpires -eq "false" -and enabled -eq "true"' |ForEach{$_.SamAccountName}
$userlist = @()
#################################################
#检测AD密码过期时间并邮件通知相应账户
##################################################
foreach ($user in $alladuser){
#密码最后一次更改时间
$pwdlastset=Get-ADUser $user -Properties * | ForEach{$_.passwordlastset}
#密码的过期时间
$pwdlastday=($pwdlastset).adddays(90)
#当前时间
$now=get-date
#判断账户是否设置了永不过期
$neverexpire=get-aduser $user -Properties * | %{$_.PasswordNeverExpires}
#距离密码过期的时间
$expire_days=($pwdlastday - $now).Days
#判断过期时间天小于7天的账户
if($expire_days -lt 7 -and $neverexpire -like "false" ){
$chineseusername= Get-ADUser $user -Properties * | ForEach {$_.Displayname}
#邮件正文
$Emailbody=
@"
<p class="MsoNormal" align="left" style="text-align: justify; margin: 0cm 0cm 0.0001pt;
font-size: 10.5pt; font-family: Calibri, sans-serif;">
<a name="_MailOriginal"><span lang="EN-US" style="font-size: 12.0pt; font-family: 宋体;
mso-bidi-font-family: 宋体; mso-font-kerning: 0pt">To </span></a><span style="font-size: 12.0pt;
font-family: 宋体; mso-bidi-font-family: 宋体; mso-font-kerning: 0pt">$chineseusername<span
lang="EN-US"> :</span></span></p>
<p class="MsoNormal" align="left" style="text-align: justify; margin: 0cm 0cm 0.0001pt;
font-size: 10.5pt; font-family: Calibri, sans-serif;">
<span style="font-size: 12.0pt; font-family: 宋体; mso-bidi-font-family: 宋体; mso-font-kerning: 0pt">
您的域账户密码即将在<span lang="EN-US"> <font
color="#ff0000">$expire_days</font> </span>天后过期,<span lang="EN-US"> <font color="#ff0000">
$pwdlastday</font> </span>之后您将无法使用该账户登陆相关系统,请您尽快在mail.bigyoung.cn上登录账户并更改密码。</span></p>
<p class="MsoNormal" align="left" style="text-align: justify; margin: 0cm 0cm 0.0001pt;
font-size: 10.5pt; font-family: Calibri, sans-serif;">
<span style="font-size: 12.0pt; font-family: 宋体; mso-bidi-font-family: 宋体; mso-font-kerning: 0pt">
&