我有一个PowerShell脚本,循环通过AD和发送电子邮件给密码在14,7,和3天到期的用户。一些个人,它的行为正常,其他时候,它会发送几封电子邮件给同一个人。
#Set Global Variables
$sender = "email@xyz.com"
$MailSubject = "Domain/VPN/Office 365: Password Expiring Notification!"
$maxPasswordAge = '90'
#Run the command to get information from Active Directory
$CommandToGetInfoFromAD = Get-ADUser -filter * -properties PasswordLastSet, PasswordExpired, PasswordNeverExpires, EmailAddress, GivenName, mail
#Loop through all users and compare dates.
$CommandToGetInfoFromAD | ForEach {
$Today = (Get-Date)
$UserName = $_.GivenName
$email = $_.mail
if (!$_.PasswordExpired -and !$_.PasswordNeverExpires) {
$ExpiryDate = ($_.PasswordLastSet+$maxPasswordAge)
$ExpiryDateForEmail = $ExpiryDate.ToString("dddd, MMMM dd yyyy a\t hh:mm tt")
$DaysLeft = ($ExpiryDate-$Today).days
$props = @{
SMTPServer = "relay.xyz"
From = $sender
To = $email
Subject = $MailSubject
}
$body = @"
<p>$UserName,</p>
<p>This is a courtesy reminder that your Domain password is set to expire on $ExpiryDateForEmail.<br>
<br>
#body removed
"@
}
if ($DaysLeft -eq 14) {
Send-MailMessage @props -body $body -BodyAsHtml -verbose
}
elseif ($DaysLeft -eq 7) {
Send-MailMessage @props -body $body -BodyAsHtml -verbose
}
elseif ($DaysLeft -eq 3) {
Send-MailMessage @props -body $body -BodyAsHtml -Verbose
}
}
它应该只发送一次给每个用户每天。它运行作为一个计划任务每天一次。有些日子它工作正常,其他日子/用户它会发送35+电子邮件。
1条答案
按热度按时间kqlmhetl1#
您的代码可以使用更好的缩进,这样更容易发现可能出错的地方。
另外,我将使用占位符
{0}
和{1}
创建主体模板Here-string,稍后将插入用户GivenName和expirydate。仅在您确定要使用它的地方创建$props
飞溅哈希表。试试看:
除了使用用户的
mail
或EmailAddress
属性之外,还可以从users的ProxyAddresses
属性中获取主电子邮件地址首先将
ProxyAddresses
附加到您要使用Get-ADUser获取的属性列表中,然后在$props
中设置To地址,如下所示: