Force User to Change Password a day before their password expires

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
		}
	}

Schedule task on AD

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 = "noreply@yourdomain.com"
     $msg.ReplyTo = "smulpuru@yourdomain.com"
     $msg.To.Add("support@yourdomain.com")
     $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)
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s