Import-Module ActiveDirectory
#定义邮件发送参数
$SMTPServer = "smtp.qq.com"
#使用了加密端口,465端口如果发送不成功,可以尝试使用587端口,这里不介绍465和587端口的区别,有兴趣的可以自行百度查询
$SMTPPort = "587"
#发送邮件的账号
$SMTPAccount = "邮箱账号"
#Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString | Out-File "D:\pwd.txt" 单独在powershell 执行即可 目录要存在
#将授权码加密
$SecureFile = "D:\pwd.txt"
$SecurePwd = Get-Content $SecureFile | ConvertTo-SecureString
$SMTPCred = New-Object System.Management.Automation.PSCredential($SMTPAccount,$SecurePwd)
#查询指定OU符合条件的用户,这里筛选了未设置密码永不过期以及账号是启用状态的用户
$AllUser = Get-ADUser -searchbase "DC=test,DC=com" -Filter 'PasswordNeverExpires -eq "false" -and enabled -eq "true"' | % {$_.SamAccountName}
#测试放松的邮箱后缀,如果有域用户有邮箱信息可以互联
$EmailLast = "@test.com.cn"
#进入循环
foreach ($User in $AllUser){
#获取上次设置密码时间
$PwdLastset = Get-ADUser $User -Properties passwordlastset | % {$_.passwordlastset}
#计算过期日期,这里是90天过期
$PwdLastday = ($PwdLastset).AddDays(90)
#获取计算机当前日期,确保运行此脚本的计算机日期准确
$Now = Get-Date
#计算密码还剩多少天过期
$ExpireDays = ($PwdLastday - $Now).Days
#执行if语句,这判断过期日期是否小于等于7并且大于0,如果为真则发送邮件
if($ExpireDays -le "7" -and $ExpireDays -gt "0"){
$DN = Get-ADUser $User -Properties Displayname | % {$_.Displayname}
#$EmailAddress = Get-ADUser $User -Properties mail | % {$_.mail} 直接获取域用户的邮箱信息 和下面的$EmailAddress = ($User+$EmailLast) 2选1执行
$EmailAddress = ($User+$EmailLast)
$EmailSubject = "您的域账号密码即将过期,请及时修改"
#编写邮件正文,可以使用html编辑器进行编辑,需要注意的是HTML源代码一定要粘贴在@" "@中间
$Emailbody =
@"
您的域账号密码将在 $ExpireDays 天之后过期,请及时修改。
"@
#发送邮件
Send-MailMessage -UseSsl -Credential $SMTPCred -From $SMTPAccount -Subject $EmailSubject -To $EmailAddress -Body $Emailbody -Encoding ([System.Text.Encoding]::UTF8) -Port $SMTPPort -SmtpServer $SMTPServer
}
}
Read-Host “Enter Password” -AsSecureString | ConvertFrom-SecureString | Out-File “D:\pwd.txt”
将授权码加密
密码为授权码不是邮箱账号密码
只需要修改 用户信息即可 DC=test,DC=com