PowerShell AD User password expires script update

Source: Internet
Author: User
Tags mailmessage

More contact with PowerShell feel like this script language, easy to understand, powerful, easy to operate, at the same time thanks to Microsoft's support, in different Microsoft product platform can be used, if you want to study Microsoft this aspect of things, will point PowerShell is definitely a lot of benefits.

Before also wrote some articles about PowerShell, also is the same as the process of their own constantly groping, and recently continued to write some scripts, some are used in the work environment, there is no way to share, some are different environments can be used, so decided to share, the script is very simple, Writing is definitely not professional, but the basic functions can be achieved.

Today and everyone to share is written a relatively simple script, the main application of the scene is also very common, is the ad environment, if the user password will expire how to even remind the user even if the password is changed, of course, Windows will regularly automatic reminders, which is also a lot of times we do not need this kind of script, a reason, But what about a different environment? For example, like our common enterprise AD environment is the company's IT operations, we will also be responsible for the operation of other ad environment, these environments may not be landing every day, or even a long time do not log in once, if the password expires, we can not see the reminder, So in this case, we need to have such a set of password expiration reminder mechanism to urge us to change the password, and if it is a weak it base company, we can also be in the mail template by adding a change password method to tell ordinary users how to modify their password, This can reduce the burden on it to a great extent.

This kind of script implementation of the method is more than one, there are many similar scripts on the Internet can be implemented such a function, but note that there are some scripts because the year is older, and then Microsoft in the ad this aspect of some updates, so in some relatively new environment (such as the server 2012 or R2 and so on) some scripts may appear to be less rigorous, such as the functionality of the granular password policy that Microsoft has introduced before, which could lead to deviations in the judgment of password expiration time.

This kind of script implementation method is basically very simple, the idea is similar, is to find out the user last password reset time, and then add the password to allow the longest period, so that the user password is the next time of expiration, However, if it is granular password policy, the actual user's allowed password maximum age will be different from other accounts in the ad, if you do not pay attention to this point, it will lead to the final judgment problems.

The bottom of the beginning to get to the point, the script to stick it out you can see for yourself, basically very simple

function logfile  ($output,  $initLog) {if  ($initLog  -eq  $True) {$input  |  out-file -filepath  $output  -encoding default -width 17384}else{$input  |  out-file -filepath  $output  -encoding default -width 17384 -append}} Function send-report{param ($LogConent, $LogPath, $MailAddress) try{send-mailmessage -from  "[Email  protected] " -To  $MailAddress  -Subject  ' Contoso password check report '  -Body  $LogConent  -Priority  ' High '  -SmtpServer mail.contoso.com -Port  25 -erroraction  ' silentlycontinue '}catch{$ErrorMessage  =  $Error [0]. exception.messagewrite-host -foregroundcolor  ' Red '   ' $ (get-date -uformat %y%m%d-%h:%m: %s) "  $ErrorMessage (" $ (get-date -uformat %y%m%d-%h:%m:%s):  " +  $ErrorMessage)  | LogFile -output  $LogPATH}} #Main  Code#Import ActiveDirectory moduleImport-Module ActiveDirectory#Log  Initialization[string] $LogDate  = Get-Date -Format  "YYYYMMDD" $LogPath  =  "c \ Passwordlogs\domainpasswordlog$logdate.txt "if  ((test-path  ' C:\PasswordLogs ')  -eq  $false) { new-item -itemtype directory  ' C:\PasswordLogs '  | out-null}#========================== ============================================================ #Get  MaxPasswordAge$RootDSE =  get-adrootdse$passwordpolicy = get-adobject  $RootDSE .defaultnamingcontext -property  maxpwdage$maxpwdage =  $PasswordPolicy .maxpwdage/-864000000000if  ($maxPwdAge  -eq 0)  -or  ($maxPwdAge  -eq  $null)) {$ErrorMessage  =  maxpasswordage is not  correct "write-host -foregroundcolor  ' Red '  " $ (get-date -uformat %y%m%d-%h:%m:%s) "  $ErrorMessage (" $ (get-date -uformat %y%m%d-%h:%m:%s):  " +  $ErrorMessage)  | logfile -output $ logpath$logconent = get-content  $LogPath  -rawSend-Report -LogConent  $LogConent  -LogPath  $LogPath  -MailAddress  ' [email protected] ' exit}#============================ ========================================================== #Check  userlist# My list of users is written in a txt document, This is because most of the users in my environment do not need this kind of email alert, their account will be maintained by US # If you need to retrieve the user to be checked in AD, you can write it directly $userlist=get-aduser -filter *| select-object -expandproperty samaccountname# like this, there's no need for $userlist =  "C:\Users\abc\ UserList.txt "if  ((test-path  $UserList)  -eq  $false) {$ErrorMessage  =  ' Can ' t  Find userlist.txt "write-host -foregroundcolor  ' Red '  " $ (get-date -uformat %y%m%d- %h:%m:%s) "  $ErrorMessage (" $ (get-date -uformat %y%m%d-%h:%m:%s):  " + $ ErrorMessage)  | logfile -output  $LogPath $logconent = get-content  $LogPath  -rawsend-report -logconent $ logconent -logpath  $LogPath  -MailAddress  ' [email protected] ' exit}#=================== =================================================================== #这里如果是使用检索AD用户的方法的话可以直接写 #foreach ($user  in  $userlist) Replace get-content to get-content  $UserList  | %{$name  =  $null $ userinfo =  $null $expiredate =  $null $passwordsetdate =  $null $today = $ null$leftdays =  $null $body =  $null $subject =  $null $individualpasswordpolicy  =  $null $outputmessage =  $null $name = $_$userinfo = get-aduser - identity  $name  -Properties *     #这里首先判断该用户信息是否存在, if there is no direct record if  ($ userinfo -eq  $null) {$ErrorMessage  =  $name  +  ": "  +  $Error [0]. Exception.messagewrite-host -foregroundcolor  ' Red '   ' $ (get-date -uformat %y%m%d-%h:%m:%s) '   $ErrorMessage ("$ (get-date  -uformat %y%m%d-%h:%m:%s):  " +  $ErrorMessage)  | LogFile -output  $LogPath}else{if  ($userinfo. passwordneverexpires -eq  $true) {     #这里记录谁的密码被设置为永久不过期了 $ErrorMessage  =   "$name ' S password has been set to neverexpires" write-host - foregroundcolor  ' Cyan '   ' $ (get-date -uformat %y%m%d-%h:%m:%s) '   $ErrorMessage ("$ ( get-date -uformat %y%m%d-%h:%m:%s):  " +  $ErrorMessage)  | logfile - output  $LogPath}else{#这里会读取颗粒化密码策略的设置, its priority should be higher than the setting of the Domain Policy $individualpasswordpolicy =  ( get-aduserresultantpasswordpolicy  $name) if  ($IndividualPasswordPolicy  -ne  $null) {$ maxpwdage =  $IndividualPasswordPolicy. maxpasswordage.totaldays} $PasswordSetDate  = $ UserInfo. Passwordlastset$expiredate =  $PasswordSetDate. AddDays ($maxPwdAge) $Today  = get-date# Compare expiration time and today, the resulting value is how many days overdue $ leftdays =  (new-timespan -start  $Today  -End  $ExpireDate). daysif  ($leftDays  -lt 0) {$body  =      Dear  $name       <p> your password has expired!!. <br>    Please change your Password as soon as  Possible so that you can work normally<br>   <p> Thanks, <br>     </p> "$subject  = " your password  has expired!! " $OutputMessage  =  "$ (get-date -uformat %y%m%d-%h:%m:%s):  $name ' s password  Has expired "write-output  $OutputMessage  | LogFile -output  $LogPath}elseif  ( $leftDays  -eq 1) {$body  =  "    dear  $name  ,    <p> Your Password will  Expire in <b><font size= ' 20px ' " color= '" Red ' ">  $leftDays  </font ></b> day!!. <br>    Please change your Password as soon as  Possible so that you can work normally <br>   <p >Thanks, <br>     </P> "$subject  = " Your password  will expire in  $leftDays  day!! " $OutputMessage  =  "$ (get-date -uformat %y%m%d-%h:%m:%s):  $name ' s password  will expire in  $leftDays  day "write-output  $OutputMessage  | logfile - output  $LogPath}elseif  ($leftDays  -le 10) {$body  =      dear   $name &NBSP;,&NBSP;&NBSP;&NBSP;&NBSP;&LT;P&GT;&NBSp Your password will expire in <b><font size= ' 20px ' " color=" "Red" >  $leftDays  </font></b> days!!. <br>    Please change your Password as soon as  Possible so that you can work normally <br>   <p >Thanks, <br>     </P> "$subject  = " Your password  will expire in  $leftDays  days "$OutputMessage  = " $ (get-date -uformat  %y%m%d-%h:%m:%s):  $name ' s password will expire in  $leftDays  days " write-output  $OutputMessage  | LogFile -output  $LogPath}else{$OutputMessage  =   "$ (get-date -uformat %y%m%d-%h:%m:%s):  $name ' s password will expire  in  $leftDays  days "write-output  $OutputMessage  | logfile -output  $LogPath} #这里设置的是如果10天以内过期的话就会发送提醒if   ($leftDays  -le 10) {      #注意如果EmailAddress为空的话就需要自己处理如何找到邮件发送的地址了 $MailAddress  =    $userinfo. emailaddressif  ($MailAddress  -ne  $null) {try{send-mailmessage -from  "[email  Protected]  -To  $MailAddress  -Subject  $subject  -Body  $body  -bodyashtml  -Priority  ' High '  -SmtpServer mail.contoso.com -Port 25 -ErrorAction  ' Silentlycontinue '}catch{$ErrorMessage  =  $Error [0]. exception.messagewrite-host -foregroundcolor  ' Red '   ' $ (get-date -uformat %y%m%d-%h:%m: %s) "  $ErrorMessage (" $ (get-date -uformat %y%m%d-%h:%m:%s):  " +  $ErrorMessage)  | LogFile -output  $LogPath}}}} #最后把这份报告发送给IT管理员if   ((test-path  $LogPath)  - eq  $true) {$LogConent  = Get-Content  $LogPath  -rawsend-report -logconent  $LogConent  -LogPath  $LogPath  -MailAddress  ' [email protected] '} 

Then set a task schedule and run the script every day.

Basically the function is realized, the overall is relatively simple

This article is from the "Just Make It Happen" blog, so be sure to keep this source http://mxyit.blog.51cto.com/4308871/1854121

PowerShell AD User password expires script update

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.