Force User to Change Password a day before their password expires

[code language=”powershell” title=”Powershell code snippet”]
Get-ADUser -Filter ‘(enabled -eq $true) -and ((passwordneverexpires -eq $false) -and (pwdlastset -ne 0 ))’ -properties MsDS-UserPasswordExpiryTimeComputed |
sort-object name | select-object Name,sAmAccountName,@{Name="PasswordExpiry";Expression={(([datetime]::fromfiletime(($_."MsDS-UserPasswordExpiryTimeComputed"))))}} | % {
if(($_.PasswordExpiry -ne $null) -and ((($_.PasswordExpiry – (Get-Date)).Days) -le 1))
{
Set-ADUser $_.Name -ChangePasswordAtLogon $true
}
}
[/code]

Schedule task on AD

[code language=”powershell” title=”Complete Powershell code”]
Import-Module ActiveDirectory
$stringbuffer = "DisplayName,PasswordExpiry`n"
$stringbuffer += "————————–`n"
$flag = $false
#pwdlastset > change password at next logon
Get-ADUser -Filter ‘(enabled -eq $true) -and ((passwordneverexpires -eq $false) -and (pwdlastset -ne 0 ))’ -properties MsDS-UserPasswordExpiryTimeComputed |
sort-object name | select-object Name,sAmAccountName,@{Name="PasswordExpiry";Expression={(([datetime]::fromfiletime(($_."MsDS-UserPasswordExpiryTimeComputed"))))}} | % {
if(($_.PasswordExpiry -ne $null) -and ((($_.PasswordExpiry – (Get-Date)).Days) -le 1))
{
$stringbuffer += $_.Name + "," + $_.PasswordExpiry.ToString("G") + "`n"
Set-ADUser $_ -ChangePasswordAtLogon $true
$flag = $true
}
}
if($flag){
#SMTP server name
$smtpServer = "your smtp server"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#Email structure
$msg.From = "[email protected]"
$msg.ReplyTo = "[email protected]"
$msg.To.Add("[email protected]")
$msg.subject = "Automation: AD Users set to change their account password"
$msg.body = "$stringbuffer `nSent from $($env:COMPUTERNAME) as Scheduled task"
#Sending email
$smtp.Send($msg)
}
[/code]

Leave a comment

Your email address will not be published. Required fields are marked *

WordPress Appliance - Powered by TurnKey Linux