I have this PowerShell script that sends out emails to managers if the user's account is expiring within a certain amount of days, however, managers get a separate email for every user. Is there a way to send only one email with the list of users?
Import-Module ActiveDirectory
#Set our non-changing variables for the email
$From = "[email protected]"
$CC = "[email protected]"
$SMTPServer = "mail.company.com"
#Get the start date, which defaults to today, and the end date which is based off the start date
$startDate = Get-Date
$endDate = $startDate.AddDays(7)
#Query AD for all the accounts between our dates and request for a couple additional properties
$Users = Get-ADUser -Filter {AccountExpirationDate -gt $startDate -and AccountExpirationDate -lt $endDate} -Properties AccountExpirationDate, Manager
#Loop through the query results
Foreach($User in $Users)
{
#The $User.Manager is not a email address, but a Distinguished Name; to get the email we can pass it to Get-Aduser though
$Manager = Get-ADUser $User.Manager -Properties EmailAddress
#Set our dynamic variables
$To = $Manager.EmailAddress
$Subject = "Account Expiration Notification for " $User.Name
$Body =
"Hello,
This notification is to inform you that the account for $($User.Name) will expire on $($User.AccountExpirationDate).
If you need to extend this, please contact HR and IT will process the request.
Thank you,
IT Help Desk"
Send-MailMessage -To $To -From $From -Subject $Subject -SmtpServer $SMTPServer -Body $Body
}
CodePudding user response: