#Primary mail variables
$SmtpServer="10.10.10.10"
$From="ADMPasswordExpiry@Midomain.es"
#Starting expire check in days
$expireindays=10
#Getting users array from all AD
$users=Get-ADuser -Properties Name, PasswordNeverExpires,
PasswordExpired, PasswordLastSet, EmailAddress -Filter *
#Loop for checking $users array in search of Fine Grained Passwords
accounts to send them expiry passwords advise mails
foreach ($user in $users) {
#Get the Name attribute for
message purposes
$Name = (Get-ADUser $user |
ForEach-Object { $_.Name })
#Check if users have
default password policy of fine grained password policy
$Check=Get-ADUserResultantPasswordPolicy $user
#Condition for discard users that have
default domain policy and execute the script only for the remaining ones
if (!$check) {
} else {
#Setting expiration
date parameter for user
$passwordSetDate =
(Get-ADUser $user -properties * | ForEach-Object {$_.PasswordLastSet})
$maxPasswordAge =
(Get-ADUserResultantPasswordPolicy $user | ForEach-Object
{$_.maxPasswordAge})
$expireson=$passwordSetDate + $maxPasswordAge
#Getting script
execution day date
$today=Get-Date
#Obtaining remaining
days to expire password for user
$daystoexpire=(New-TimeSpan -Start $today -End $Expireson).Days
#Obtaining mail
attribute from user
$emailaddress=$user.EmailAddress
#Condition that
executes the mail advise if remaining days for password expiration are less
than $expireindays variable and if is not expired (0 days remaining)
If (($daystoexpire -ge
"0") -and ($daystoexpire -lt $expireindays)) {
$EmailBody="Te
quedan $daystoexpire dias para cambiar la contraseña de tu usuario
$name."
}
#Email subject
$EmailSubj="Aviso de caducidad de password de tu usuario
administrador"
#Create and send an
email object
$SMTPClient =
New-Object Net.Mail.SMTPClient($SmtpServer)
$emailMessage =
New-Object System.Net.Mail.MailMessage
$emailMessage.From
= "$From"
Foreach($EmailTo in
$emailaddress)
{
$emailMessage.To.Add($EmailTo)
}
$emailMessage.Subject = "$EmailSubj"
$emailMessage.Body
= "$EmailBody"
$SMTPClient.Send($emailMessage)
}
Else {
#No pending password expire
}
}
}
|