您可以创建一个PSObject,其中包含
foreach
循环,然后使用该列表发送已填充PSObjects的单个电子邮件。
注意:我还没有测试过这个,因为我现在没有访问广告环境的权限,但是应该非常接近…
$MaxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
$Properties = @("PasswordLastSet","PasswordExpired","DisplayName")
$PasswordExpired = @()
$OneDayLeft = @()
$SMTPServer = "x.x.x.x"
$today = Get-Date
Get-ADUser -Filter "Enabled -eq $True -and PasswordNeverExpires -eq $False" -Properties $Properties | foreach {
$DisplayName = $_.DisplayName
$ExpiryDate = $_.PasswordLastSet + $maxPasswordAgeTimeSpan
$DaysLeft = ($ExpiryDate-$today).days
If ($_.PasswordExpired -like 'True') {
#Add user to PasswordExpired PSObject if password expired:
$PasswordExpired += New-Object -TypeName PSObject -Property @{User="$DisplayName"}
}
ElseIf ($DaysLeft -eq 1) {
#Add user to OneDayLeft PSObject if password expiring soon:
$OneDayLeft += New-Object -TypeName PSObject -Property @{User="$DisplayName"; ExpiryDate="$ExpiryDate"}
}
}
#Use PSObject to create a HTML Table:
$PasswordExpired_Table = $PasswordExpired | ConvertTo-Html -Fragment
$OneDayLeft_Table = $OneDayLeft | ConvertTo-Html -Fragment
#Assemble Email Body string using HTML Table of data:
$PasswordExpired_Body = "<p style='font-family:arial'>Hi,</p>
<p style='font-family:arial'>Expired passwords:</p>
<p style='font-family:arial'>$PasswordExpired_Table</p>
<p style='font-family:arial'>Thanks.</p>"
$OneDayLeft_Body = "<p style='font-family:arial'>Hi,</p>
<p style='font-family:arial'>Passwords expiring soon:</p>
<p style='font-family:arial'>$OneDayLeftTable</p>
<p style='font-family:arial'>Thanks.</p>"
Send-MailMessage -to "xxx@xxx.com" -from "x@x.com" -Subject "Mot de passe Windows" -body $PasswordExpired_Body -smtpserver $SMTPServer -BodyAsHtml -Encoding UTF8
Send-MailMessage -to "x@x.com" -from "x@x.com" -Subject "Mot de passe Windows va expirer demain" -body $OneDayLeft_Body -smtpserver $SMTPServer -BodyAsHtml -Encoding UTF8