Advertisement
ShiftNick

Find stale user, email users afterwards

Apr 10th, 2015
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #FINDING THE USERS TO DISABLE
  2. #Variables
  3. $DaysInactive = 91  
  4. $time = (Get-Date).Adddays(-($DaysInactive))
  5. $SearchBase = "OU=Users,OU=Site,DC=Domain,DC=Local"
  6. $date = Get-date -Format ddMMyyyy
  7.  
  8. #Finds users defined in Searchbase that are enabled and the last log on was more than the $DaysInactive variable.
  9. Get-ADUser -SearchBase $SearchBase -Filter {LastLogonTimeStamp -lt $time -and Enabled -eq $true} -Properties samAccountName,Name,EmailAddress,LastLogonTimeStamp | Select-object -Property samAccountName,Name,EmailAddress,@{N='LastLogonTime'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp).ToString('d MMMM yyyy')}} | Export-CSV -Path "c:\Script\UsersToDisable$Date.CSV"
  10.  
  11. #EMAILING USERS YOUR ARE DISABLING - RENAME YOUR CSV TO SOMETHING SIMPLE BEFORE DOING THIS
  12.  
  13. $smtpServer="smtp.server.com"
  14. $from = "Email Address <me@me.com>"
  15. $days = "# of Days"
  16. $subject="Your account will expire in $Days"
  17. $Users = Import-CSV -Delimiter "," -Path "c:\Script\UsersToDisable.CSV"
  18.  
  19. ForEach ($User in $Users)
  20. {
  21. $to = $user.EmailAddress
  22. $name = $user.Name
  23. $stale = $user.LastLogonTime
  24.  
  25. $emailbody = "<font face=Arial Size=2>
  26. Hello $Name,
  27. <p> You have not logged in to your account since $stale and it will be disable in $days days, unless you respond to this message</p>
  28. </br>
  29. <p>Thanks,</p>
  30. </br>
  31. <p>Your friendly neighbourhood IT Guy</p>
  32. </font>"
  33.  
  34.  # Send Email Message
  35.  Send-Mailmessage -smtpServer $smtpServer -from $from -to $to -subject $subject -body $body -bodyasHTML -priority High
  36. }
  37.  
  38. #DISABLE THE USER ACCOUNTS
  39. $users = Import-CSV -Delimiter "," -Path "c:\Script\UsersToDisable.CSV"
  40.  
  41. ForEach ($User in $Users)
  42. {
  43. $SAM = $User.samAccountName
  44.  
  45. Set-Aduser -Identity $SAM -enabled $false
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement