关于AD域用户密码过期发送邮件
powershell吧
全部回复
仅看楼主
level 1
获取到了域即将密码过期的用户,但是这个代码发邮件会发送多封,例如我有三个用户,他就会1,1+2,1+2
+3
,这样子发送三封邮件,以下是代码,求助怎么才能整合到一封邮件里发送出来呢?
Import-Module Activedirectory
$alladuser=get-aduser -searchbase "ou=x,dc=xp,dc=com" -filter * | %{$_.Samaccountname}
#上面的“ou=***,dc=***,dc=***” 根据自己域结构实际情况填写
$userlist = @()
echo $alladuser#显示所有用户
#echo $userlist
$itmag = "[email protected]" #IT管理员的邮件地址
function sendmail($mailaddr,$body) #定义发送邮件的方法
{
$msg=New-Object System.Net.Mail.MailMessage
$msg.To.Add($mailaddr)
#$msg.Bcc.Add($itmag)#抄送给管理员
$msg.From = New-Object System.Net.Mail.MailAddress("[email protected]", "password",[system.Text.Encoding]::GetEncoding("UTF-8")) #发件人
$msg.Subject = "邮件密码即将过期"
$msg.SubjectEncoding = [system.Text.Encoding]::GetEncoding("UTF-8")
$msg.Body =$body
#$Attachments=New-Object System.Net.Mail.Attachment("D:\Documents\xxxx.zip")#创建附件
#$msg.Attachments.add($Attachments) #添加附件,英文名可多个,中文名就只能带一个。
$msg.BodyEncoding = [system.Text.Encoding]::GetEncoding("UTF-8")
$msg.IsBodyHtml = $true#发送html格式邮件
#$msg.Priority = [System.Net.Mail.MailPriority]::High
$client = New-Object System.Net.Mail.SmtpClient("smtp.qq.com") #配置smtp服务器
$client.Port = 587#指定smtp端口
$client.EnableSsl = $true #带ssl功能的smtp服务器
$client.UseDefaultCredentials = $false
$client.Credentials=New-Object System.Net.NetworkCredential("[email protected]", "password")
try {$client.Send($msg)}
catch [Exception]
{$($_.Exception.Message)
$mailaddr
}
}
foreach ($user in $alladuser)
{
#密码最后一次更改时间
$pwdlastset=Get-ADUser $user -Properties * | %{$_.passwordlastset}
#密码的过期时间
$pwdlastday=$pwdlastset.AddDays(30)
#当前时间
$now=get-date
#判断账户是否设置了永不过期
$neverexpire=get-aduser $user -Properties * |%{$_.PasswordNeverExpires}
#距离密码过期的时间
$expire_days=($pwdlastday - $now).Days
#判断过期时间天小于5天大于-5天(即已过期5天)的并且没有设置密码永不过期的账户
if($expire_days -lt 60 -and $expire_days -gt -5 -and $neverexpire -like "false" )
{
$chineseusername= Get-ADUser $user -Properties * | %{$_.Displayname}
#邮件正文
$EmailbodyHTML=
$username=Get-ADUser $user -Properties *
$userobject=New-object psobject
$userobject | Add-Member -membertype noteproperty -Name 用户名 -value $username.displayname
$userobject | Add-Member -membertype noteproperty -Name 邮箱 -Value $username.mail
$userobject | Add-Member -membertype noteproperty -Name 最后一次密码设置 -Value $username.Passwordlastset
$userobject | Add-Member -membertype noteproperty -Name 密码过期时间 -Value $pwdlastday
$userobject | Add-Member -membertype noteproperty -Name 距离密码过期天数 -Value $expire_days
$userlist+=$userobject
$EmailbodyHTML=$userlist|
sort-object 距离密码过期天数 |
ConvertTo-Html |
Out-String
$tomailaddr = "[email protected]"
#echo $tomailaddr
sendmail $tomailaddr $EmailbodyHTML
}
}
2020年02月07日 02点02分 1
level 1
已解决
2020年02月07日 03点02分 2
level 1
还没有弄明白,能指导一下面,谢谢
2020年06月28日 05点06分 3
level 1
怎么不重复发呢,能告知吗
2021年03月29日 09点03分 4
1