Reputation: 23
I'm trying to create a PowerShell script that will search my Active Directory for users with passwords that will expire in 14 days and email the user a reminder message. For the most part I have the script working as intended, but I am not getting the proper output for the emails.
This is the script:
Import-Module ActiveDirectory
$below = (Get-Date).AddDays(-77)
$above = (Get-Date).AddDays(-76)
$Persons = Get-ADUser -Filter {PasswordNeverExpires -eq $False -AND (PasswordLastSet -lt $above -AND PasswordLastSet -gt $below) -AND (LastLogonDate -like "*") -AND (MAil -like "*")}
foreach ($Person IN $Persons) {
$body = "Your Windows password will expire in 14 days. Please consider changing your password. - $User.Name - $User.PasswordLastSet"
Send-MailMessage -To $User.Mail -Subject "Alert! Password Expiring Soon!" -From '[email protected]' -Body $body -SmtpServer smtp.server.com
}
This is what I am getting in the body of the mails it sends.
Your Windows password will expire in 14 days. Please consider changing your password. - .Name - .PasswordLastSet
How do I pass the users name and password last set data to the body text?
Upvotes: 2
Views: 11697
Reputation: 47772
An alternative to iCodez's (correct) answer is to use the format operator (-f
):
$body = "...your password. - {0} - {1}" -f $User.Name,$User.PasswordLastSet
Upvotes: 1
Reputation:
You need to use subexpressions $(...)
to access the properties on $User
in the string:
"... - $($User.Name) - $($User.PasswordLastSet)"
Otherwise, PowerShell will only parse $User
as a variable and the .Name
and .PasswordLastSet
parts will be treated as normal text.
Upvotes: 5