Archive for category Active Directory

Powershell Script to Disable Inactive Users v3

Purpose:
Disable users that have been inactive for 90 days.
Not to disable newly created accounts unless they are not used in 30 days.

Notes:

v1 can be found here: https://randomtechminutia.wordpress.com/2013/07/09/script-to-disable-inactive-users/
v2 can be found here: http://vnucleus.com/2011/07/use-powershell-to-auto-disable-inactive-active-directory-accounts/ (Link is now bad)
Must be run with an Account that has rights to disable and move User Accounts
Must have QAD Powershell cmdlets installed.

Example Email:

disableinactiveuserexample

Code:


#=====================================================================================================#
#    Copyright 2011 Robert Stacks
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#=====================================================================================================#
# Author: David Beasley
# Updated: Robert Stacks
# Original Script URL: http://vnucleus.com/2011/07/use-powershell-to-auto-disable-inactive-active-directory-accounts/
# Updated Script URL: https://randomtechminutia.wordpress.com/2014/07/09/powershell-script-to-disable-inactive-users-v3/
# Date: 7/26/2011
# Updated: 7/9/2014
# Verson: 0.6
#
# Purpose:
# Disable Inactive Active Directory Accounts
#
# Update Notes:
# 7/9/2014 - Robert Stacks
# - Added remote domain functionality
# - Added user option to enable/disable moving of disabled accounts
# - Updated the Report with a CSS Style Sheet and overall improved formatting
# - Added Creation Date column
# - Added DN Column which shows DN prior to move to disabled OU so if someone needs to re-enable an account they can move it back to the correct OU
#
#=====================================================================================================#

#===========================#
#User Adjustable Variables  #
#===========================#

#Account with rights to remotely log into domain
$AdminAcct = 'domain.local\AdminAcct'
$Adminpwd = 'password'

#Domain to Log into
$domain = 'domain.local'

#Company Name - Used for Report
$CompanyName = 'Company Name'

# Query Options #
$searchRoot = "domain.local/" # Where to begin your recursive search - If you use top-level (e.g. "domain.local/") make sure to have a trailing slash, otherwise do not use a slash (e.g. "domain.local/Users")
$inactiveDays = 90 # Integer for number of days of inactivity (e.q. 90)
$timeSinceCreation = 30 # Integer for number of "grace" days since the account was created (to prevent disabling of brand new accounts)
$sizeLimit = 0 # How many users do you want returned. 0 = unlimited. Without setting this the default is 1000

# Action Options #
$MovedisabledAccount = 0 # 0 = disabled or 1=enabled Defines if the script will move a disabled account
$disabledOU = "domain.local/Users/Disabled" # Define where disabled accounts are stored (e.g. "domain.local/Users/Disabled")

# Email Settings #
$emailAlerts = 1 # Turn e-mail alerts on or off. 0 = off 1 = On
$fromAddr = "ADInactiveAccounts@domain.COM" # Enter the FROM address for the e-mail alert
$toAddr = "sysadmins@domain.com" # Enter the TO address for the e-mail alert
$smtpsrv = "mail.domain.com" # Enter the FQDN or IP of a SMTP relay

# Enable Script #
$enableAction = 0 # Change to 0 if you want to "whatif" this script - It will bypass the actual account disabling (turn e-mail alerts on!)

#===========================#
#Main Script                #
#===========================#

$date = Get-Date -Format d

# Format html report with CSS
$htmlReport = @"
<style type='text/css'>
.heading {
color:white;
font-size:14.0pt;
font-weight:700;
font-family:Verdana, sans-serif;
text-align:left;
vertical-align:middle;
height:20.0pt;
width:416pt;
background:#1975D1

}
.colnames {
color:white;
font-size:10.0pt;
font-weight:700;
font-family:Tahoma, sans-serif;
text-align:center;
vertical-align:middle;
border:.5pt solid white;
background:#3385FF;
}
.textcolor1 {
color:windowtext;
font-size:9.0pt;
font-family:Arial;
text-align:center;
vertical-align:middle;
border:1pt solid windowtext;
background:#C1D0E6;
}
.textcolor2 {
color:windowtext;
font-size:9.0pt;
font-family:Arial;
text-align:center;
vertical-align:middle;
border:1pt solid windowtext;
background:white;
}
</style>
<table border=0 cellpadding=4 cellspacing=1 width=auto
style='border-collapse:collapse;table-layout:auto;width:auto'>
<tr style='height:15.0pt'>
<th rowspan=3 colspan=5 height=40 width=auto class="heading">
<center>$CompanyName</center>
<center>Report:$($inactiveUsers.Count) User Accounts Disabled Due to Inactivity</center>
<center>Date: <i> $date </i> Domain: <i> $domain </i></center>
</th>
</tr>
<tr></tr>
<tr>
<th class="colnames">Name</th>
<th class="colnames">Account</th>
<th class="colnames">Creation Date</th>
<th class="colnames">Last Login</th>
<th class="colnames">DN</th>
</tr>
"@

Add-PSSnapin "Quest.ActiveRoles.ADManagement"

#Set User account to be used to log into cross site domain without AD Trust
$username = $AdminAcct
$password = ConvertTo-SecureString $Adminpwd -AsPlainText -Force
$livecrd = New-Object System.Management.Automation.PSCredential $username, $password

#Connect to the specific domain
Connect-QADService -Service $domain -Credential $livecrd

#Cutoff Date
$creationCutoff = (Get-Date).AddDays(-$timeSinceCreation)

#Get list of inactive user accounts
$inactiveUsers = @(Get-QADUser -SearchRoot $searchRoot -Enabled -NotLoggedOnFor $inactiveDays -CreatedBefore $creationCutoff -SizeLimit $sizeLimit | Select-Object Name,SamAccountName,CreationDate,LastLogonTimeStamp,Description,DN | Sort-Object Name)

# Counter for color in table
$i = 0

# Generate table
do {
if($i % 2)
{$htmlReport += "<tr class='textcolor1'><td>$($inactiveUsers[$i].Name)</td><td>$($inactiveUsers[$i].SamAccountName)</td><td>$($inactiveUsers[$i].CreationDate)</td><td>$($inactiveUsers[$i].LastLogonTimestamp)</td><td>$($inactiveUsers[$i].DN)</td></tr>";$i++}
else
{$htmlReport += "<tr class='textcolor2'><td>$($inactiveUsers[$i].Name)</td><td>$($inactiveUsers[$i].SamAccountName)</td><td>$($inactiveUsers[$i].CreationDate)</td><td>$($inactiveUsers[$i].LastLogonTimestamp)</td><td>$($inactiveUsers[$i].DN)</td></tr>";$i++}
}
while ($inactiveUsers[$i] -ne $null)

# Finish create of Table
if($MovedisabledAccount -eq 1){
$htmlReport += @"
<th colspan=5 height=40 width=auto class="footer">
 <center>Note: Disabled Computer Objects moved to this OU: <i>$disabledOU</i></center></th>
</tr>
</table></center>
"@
}
else{
$htmlReport += @"
<th colspan=5 height=40 width=auto class="footer">
 <center>Note: Disabled Computer Objects where not moved during this operation.</center></th>
</tr>
</table></center>
"@
}

# Disable Accounts #
if ($enableAction -eq 1 -and $inactiveUsers -ne $null){
 foreach($user in $inactiveUsers){
 Set-QADUser $user.SamAccountName -Description "Account Disabled on $date for Inactivity - $($user.Description)" | Disable-QADUser
  #Move Disabled Accounts to Disabled OU
  if ($MovedisabledAccount -ne 0){
   Move-QADObject $user -NewParentContainer $disabledOU
   }
 }
}

### Email Alerts ###
if ($emailAlerts -eq 1 -and $inactiveUsers -ne $null){

Send-MailMessage -To $toAddr -From $fromAddr -Subject "AutoDisable Report for $($domain): $($inactiveUsers.Count) User Accounts Disabled on $date" -Body "$htmlReport" -SmtpServer $smtpsrv -BodyAsHtml
}

#Disconnect from AD Cleanly
Disconnect-QADService

exit

 

 

Advertisements

3 Comments

Powershell Script to Disable inactive Users

Purpose:
Disable users that have been inactive for 90 days.

Notes:
Have not improved format yet.

Must be run on a DC with Domain Admin rights.

# Get today's date
$date = get-date

# Set variable LLTSlimit to today's date minus 90 days
$LLTSlimit = (Get-Date).AddDays(-90).ToFileTimeUTC().ToString()

# Set variable LDAPfilter as a LDAP filter to only find ACTIVE user accounts (useraccountcontrol piece) that have a lastlogontimestamp of older than 90 days
$LDAPFilter = "(&(objectCategory=Person)(objectClass=User)(lastlogontimestamp<=$LLTSlimit)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" #output LDAPfilter to txt file for loop dsquery * domainroot -filter $LDAPFilter -limit 0 > D:\scripts\AD Auto Disable\ADUserstoDisable.txt

#if LDaPfilter is not null, we will disable some accounts and send a email else do nothing.
if (($ldapcontent = get-content "D:\scripts\AD Auto Disable\ADUserstoDisable.txt") -ne $NULL)
{

    # Pre-create file to store query results
ECHO "Summary of Users Disabled Due To Inactivity" >  D:\scripts\AD Auto Disable\AutoDisableResults.txt
ECHO "*--------------------------------------------------------*" >> D:\scripts\AD Auto Disable\AutoDisableResults.txt

#Loop through the users that need to be disabled one at a time
FOREACH ($f in get-content D:\scripts\AD Auto Disable\ADUserstoDisable.txt)
{
#Add the user to be disabled to txt file to be emailed out.
$f>>D:\scripts\AD Auto Disable\AutoDisableResults.txt

#get the old description so it can be appended
$olddesc = dsget user $f -desc
$olddesc > D:\scripts\AD Auto Disable\olddesc.txt
$processolddesc = get-content "D:\scripts\AD Auto Disable\olddesc.txt"
$processolddesc = $processolddesc[1]

Update:
There is a better version of this script over at vNucleus.com that David wrote:
http://vnucleus.com/2011/07/use-powershell-to-auto-disable-inactive-active-directory-accounts/

David recently sold his domain and this link no longer works.  As soon as he republishes his site I’ll update the link.

A newer version can now be found here: http://wp.me/p1VY3A-7R

Leave a comment

Simple Powershell Script to Disable PCs that have been inactive in AD for 90 Days.

Purpose:
Find PC’s that have been inactive for more than 90 days

Notes:
I haven’t formated this script in the typical fashion I normally do.

Must be run on a DC with Domain Rights.

# Get today's date
$date = get-date

# Set variable LLTSlimit to today's date minus 90 days
$LLTSlimit = (Get-Date).AddDays(-90).ToFileTimeUTC().ToString()

# Set variable LDAPfilter as a LDAP filter to only find ACTIVE user accounts (useraccountcontrol piece) that have a lastlogontimestamp of older than 90 days
$LDAPFilter = "(&(objectCategory=Computer)(objectClass=User)(lastlogontimestamp<=$LLTSlimit)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"

#output LDAPfilter to txt file for loop
dsquery * domainroot -filter $LDAPFilter -limit 0 > D:\scripts\test.txt

#Loop through the computers that need to be disabled one at a time
FOREACH ($f in get-content D:\scripts\test.txt)
{

#disable computer and append to the old description the note about disabling account
dsmod computer $f -disabled yes -desc "$processolddesc - Disabled due to inactivity on $date"

}

exit

Leave a comment

Set AD Email Address to PrimarySmtpAddress in matching Exchange Contact

Synopsis
I wrote this little script to address a issue where another admin/help desk/etc created a bunch of exchange contacts for external users and then later we ended up creating some AD accounts for some of those users so they could access some Linux/Unix systems we host. However we ran into a issue where those users had no way to be notified of password’s expire. So to address that I wrote this script Powershell Script to Notify Users of Expired or About to Expire Passwords in Active Directory which worked fine but then I found I couldn’t email some users because I didn’t have a email address for them. I did however have an exchange contact for some of them. So I wrote the follow script to copy their emails from the exchange contact into the AD Email attribute.

Requirements to run script:

Other Notes:
You will see some errors with this script if the Get-MailContact fails to find any info for the user in question. This is ok and is expected.

#Add Snapins
Add-PSSnapin "Quest.ActiveRoles.ADManagement" -ErrorAction SilentlyContinue

$users = Get-QADUser -SearchRoot 'OU=INTERNATIONAL OFFICE USERS,DC=domain,DC=net' -Enabled -PasswordNeverExpires:$false | where {($_.Email -eq $null)}

Foreach ($user in $users)
{
	$contact = Get-MailContact -Identity $user.Name
	if ($contact -ne $null)
	{
		Set-QADUser $user.Name -Email $contact.PrimarySmtpAddress
	}
	
}

Leave a comment

How to fix the issue of a user not showing up in the Global Address book.

This little one liner can possibly fix a issue where a user doesn’t show up in the Global Address book.

To run the following powershell script, you must be a Domain Admin and an Exchange Admin.

get-mailbox -resultsize unlimited | Where-Object {$_.PrimarySMTPAddress -ne $_.WindowsEmailAddress} 
| foreach { set-mailbox $_.identity -windowsemailaddress $_.primarySMTPAddress }

Explanation:
This Script will set the Email address field found in Active Directory Users and Computers for a User/Object that has a email account in Exchange to the same value as that set in Exchange as that of the User/Object’s primary SMTP email address.

This will fix the issues where the users doesn’t show up in the global address book.

Finally after running the script you must update the OAB in exchange and all clients must update their local address books by running send and receive.

MS Technet Support Article
http://support.microsoft.com/kb/936197

, , ,

Leave a comment

Powershell Script to Notify Users of Expired or About to Expire Passwords in Active Directory.

So where I work we use AD for single sign on (sso) for many of our systems both Windows and Nix. Some of our users only access the Nix systems and are not actually on our domain. They have no way of knowing when their passwords are about to expire and when their passwords do expire they just can’t log in without any visible reason why. In order to address that I started looking around the net for a powershell script and found one over at Dan Penning Blog but it didn’t address all of my needs. So using Dan’s script as the basis for a new script I came up with the following.

Synopsis of Goal:
Email the User when their password is about to expire or has expired and Supply a URL Link to reset their password.
Notify the Admin of certain conditions

  • Users Have Expired Passwords And No Primary SMTP Address to notify them
  • Users Password’s is About To Expire That Have No Primary SMTP Address
  • Users With Expired Passwords – Purely to report on it
  • Users Password’s About To Expire
  • Users with no Expiration Date

And Supply the Admin with the Location of the User account in question in the report.

Other Notes:
Included Options in the script without major rewrite

  • Adjust timing to being alerting (default is at 10 days start sending alerts to the user.)
  • Admin report is optional
  • Admin report can be sorted by Password Expiration, First, or Last Name.
  • Alerting Users is optional
  • Assign self service URL
  • Adjustable From Address and Relay Mail Server.
  • Change Font size and style for majority of text
#=====================================================================================================#
#    Copyright 2011 Robert Stacks
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#=====================================================================================================#
# Author: Robert Stacks
# URL: RandomTechMinutia.wordpress.com
# Updated: 06/21/2012
# Version: 1.2
#
# Based on a script by Dan Penning http://danpenning.com
#
# Purpose:
# Powershell script to find out a list of users
# whose password is expiring within x number of days (as specified in $days_before_expiry).
# Email notification will be sent to them reminding them that they need to change their password.
#
# Requirements:
# Quest ActiveRoles cmdlets (http://www.quest.com/powershell/activeroles-server.aspx)
# Powershell 2.0 ~ may work in 1.0 but I haven't tested it.
#
# Script must be run as a user with Permission to view AD Attributes, Domain Admin for example.
#
#=====================================================================================================#
#Add Snapins
Add-PSSnapin "Quest.ActiveRoles.ADManagement" -ErrorAction SilentlyContinue

#Get todays date for use in the script
$date = Get-Date

#===========================#
#User Adjustable Variables  #
#===========================#

# How many Days Advanced Warning do you want to give?
$DaysOfNotice = 10

#Generate a Admin report?
$ReportToAdmin = $true
#$ReportToAdmin = $false

#Sort Report
#===========================#
# 0 = By OU
# 1 = First Name Ascending
# 2 = Last Name Ascending
# 3 = Expiration Date Ascending
# 4 = First Name Descending
# 5 = Last Name Descending
# 6 = Expiration Date Descending
#===========================#
$ReportSortBy=1

#Alert User?
#$AlertUser = $true
$AlertUser = $false

#URL for self Service
$URLToSelfService = "http://"

#Mail Server Variables
$FromAddress = "DoNotReply@yourdomain.com"
$RelayMailServer = "mail.yourdomain.com"
$AdminEmailAddress ="Admin@yourdomain.com"

# Define font and font size
# ` or \ is an escape character in powershell
$font = "<font size=`"3`" face=`"Calibri`">"

# List of users whose Password is about to expire. The following line can be added to limit OU's searched if so desired
#$users += Get-QADUser -SearchRoot 'DN' -Enabled -PasswordNeverExpires:$false | where {($_.PasswordExpires -lt $date.AddDays($DaysOfNotice))}
#$users = Get-QADUser -SearchRoot 'OU= Company USERS,DC=contoso,DC=com' -Enabled -PasswordNeverExpires:$false | where {($_.PasswordExpires -lt $date.AddDays($DaysOfNotice))}
#$users += Get-QADUser -SearchRoot 'OU=INTERNATIONAL OFFICE USERS,DC=contoso,DC=com' -Enabled -PasswordNeverExpires:$false | where {($_.PasswordExpires -lt $date.AddDays($DaysOfNotice))}

# Search Whole Root
$users = Get-QADUser -Enabled -PasswordNeverExpires:$false | where {($_.PasswordExpires -lt $date.AddDays($DaysOfNotice))}

#===========================#
#Main Script                #
#===========================#

# Sort Report
Switch ($ReportSortBy)
{
'0' {$users}
'1' {$users = $users | sort {$_.FirstName}}
'2' {$users = $users | sort {$_.LastName}}
'3' {$users = $users | sort {$_.PasswordExpires}}
'4' {$users = $users | sort -Descending {$_.FirstName}}
'5' {$users = $users | sort -Descending {$_.LastName}}
'6' {$users = $users | sort -Descending {$_.PasswordExpires}}
}

if ($ReportToAdmin -eq $true)
{
#Headings used in the Admin Alert
$Title="<h1><u>Password Expiration Status and Alert Report</h1></u><h4>Generated on " + $date + "</h4>"
$Title+="<font color = red><h2><u>Admin Action Required</h2></u></font>"
$Title+="<font size=`"3`" color = red> An Admin needs to update these accounts so that users can be notified of pending or past password experation<br></font>"
$Title_ExpiredNoEmail="<h3><u>Users Have Expired Passwords And No Primary SMTP to Notify Them</h3></u>"
$Title_AboutToExpireNoEmail="<h3><u>Users Password's Is About To Expire That Have No Primary SMTP Address</h3></u>"
$Title2="<br><br><h2><u><font color= red>No Admin Action Required - Email Sent to User</h2></u></font>"
$Title_Expired="<h3><u>Users With Expired Passwords</h3></u>"
$Title_AboutToExpire="<h3><u>Users Password's About To Expire</h3></u>"
$Title_NoExpireDate="<h3><u>Users with no Expiration Date</u></h3>"
}
#For loop to report
foreach ($user in $users)
{

if ($user.PasswordExpires -eq $null)
{
$UsersList_WithNoExpiration += $user.Name + " (<font color=blue>" + $user.LogonName + "</font>) does not seem to have a Expiration Date on their account.<font color=Green> <br>OU Container: " + $user.DN + "</font> <br>"
}
Elseif ($user.PasswordExpires -ne $null)
{
#Calculate remaining days till Password Expires
$DaysLeft = (($user.PasswordExpires - $date).Days)

#Days till password expires
$DaysLeftTillExpire = [Math]::Abs($DaysLeft)

#If password has expired
If ($DaysLeft -le 0)
{
#If the users don't have a primary SMTP address we'll report the problem in the Admin report
if (($user.Email -eq $null) -and ($user.UserMustChangePassword -ne $true) -and ($ReportToAdmin -eq $true))
{
#Add it to admin list to report on it
$UserList_ExpiredNoEmail += $user.name + " (<font color=blue>" + $user.LogonName + "</font>) password has expired " + $DaysLeftTillExpire + " day(s) ago</font>. <font color=Green> <br>OU Container: " + $user.DN + "</font> <br><br>"
}

#Else they have an email address and we'll add this to the admin report and email the user.
elseif (($user.Email -ne $null) -and ($user.UserMustChangePassword -ne $true) -and ($AlertUser -eq $True))
{
$ToAddress = $user.Email
$Subject = "Friendly Reminder: Your Corporate Password has expired."
$body = " "
$body = $font
$body += "Greetings, <br><br>"
$body += "This is a auto-generated email to remind you (<font color=blue> " + $user.Name + "</font>) that your Corporate Password for account - <font color=red>" + $user.LogonName + "</font> - has expired. <br><br>"
$body += "This means you will not be able to access any secured system hosted at the Corporate Offices.<br><br> You can log into " + $URLToSelfService + " "
$body += "and reset the password yourself, else you are welcome to contact the Service Desk by Phone for assistance."
$body += "<br><br><br><br>"
$body += " "
$body += "<h4>Never Share Your Password With Others!</h4>"
$body += "<h5>Message generated on: " + $date + ".</h5>"
$body += "</font>"

Send-MailMessage -smtpServer $RelayMailServer -from $FromAddress -to $user.Email -subject $Subject -BodyAsHtml  -body $body

}
if ($ReportToAdmin -eq $true)
{
#Add it to a list
$UserList_ExpiredHasEmail += $user.name + " (<font color=blue>" + $user.LogonName + "</font>) password has expired " + $DaysLeftTillExpire + " day(s) ago</font>. <font color=Green> <br>OU Container: " + $user.DN + "</font> <br><br>"
}
}
elseif ($DaysLeft -ge 0)
{
#If Password is about to expire but the user doesn't have a primary address report that in the Admin report
if (($user.Email -eq $null) -and ($user.UserMustChangePassword -ne $true) -and ($ReportToAdmin -eq $true))
{
#Add it to admin list
$UserList_AboutToExpireNoEmail += $user.name + " (<font color=blue>" + $user.LogonName + "</font>) password is about to expire and has " + $DaysLeftTillExpire + " day(s) left</font>. <font color=Green> <br>OU Container: " + $user.DN + "</font> <br><br>"
}
# If there is an email address assigned to the AD Account send them a email and also report it in the admin report
elseif (($user.Email -ne $null) -and ($user.UserMustChangePassword -ne $true) -and ($AlertUser -eq $True) )
{
#Setup email to be sent to user
$ToAddress = $user.Email
$Subject = "Notice: Your Corporate Password is about to expire."
$body = " "
$body = $font
$body += "Greetings, <br><br>"
$body += "This is a auto-generated email to remind you (<font color=blue> " + $user.Name + "</font>) that your Corporate Password for account - <font color=red>" + $user.LogonName + "</font> - will expire in </font color = red>" + $DaysLeftTillExpire +" Day(s). <br><br>"
$body += "This means you will not be able to access any secured system hosted at the Corporate Offices.<br><br> You can log into " + $URLToSelfService + " "
$body += "and reset the password yourself, else you are welcome to contact the Service Desk by Phone for assistance."
$body += "<br><br><br><br>"
$body += "<h4>Never Share Your Password With Others!</h4>"
$body += "<h5>Auto-Generated Message On: " + $date + ".</h5>"
$body += "</font>"

Send-MailMessage -smtpServer $RelayMailServer -from $FromAddress -to $user.Email -subject $Subject -BodyAsHtml  -body $body

}
if ($ReportToAdmin -eq $true)
{
#Add it to admin Report list
$UserList_AboutToExpire += $user.name + "  <font color=blue>(" + $user.LogonName + "</font>) password is about to expire and has " + $DaysLeftTillExpire + " day(s) left</font>. <font color=Green> <br>OU Container: " + $user.DN + "</font> <br><br>"
}
}
}
} # End foreach ($user in $users)

if ($ReportToAdmin -eq $true)
{
If ($UserList_AboutToExpire -eq $null)  {$UserList_AboutToExpire = "No Users to Report"}
If ($UserList_AboutToExpireNoEmail -eq $null){ $UserList_AboutToExpireNoEmail = "No Users to Report"}
if ($UserList_ExpiredHasEmail -eq $null) {$UserList_ExpiredHasEmail = "No Users to Report"}
if ($UserList_ExpiredNoEmail -eq $null) {$UserList_ExpiredNoEmail = "No Users to Report"}
if ($UsersList_WithNoExpiration -eq $null) {$UsersList_WithNoExpiration = "No Users to Report"}

#Email Report to Admin
$Subject="Password Expiration Status for " + $date + "."
$AdminReport = $font + $Title + $Title_ExpiredNoEmail + $UserList_ExpiredNoEmail + $Title_AboutToExpireNoEmail + $UserList_AboutToExpireNoEmail + $Title_AboutToExpire + $UserList_AboutToExpire + $Title_Expired + $UserList_ExpiredHasEmail + $Title_NoExpireDate + $UsersList_WithNoExpiration + "</font>"
Send-MailMessage -smtpServer $RelayMailServer -from $FromAddress -to $AdminEmailAddress -subject $Subject -BodyAsHtml -body $AdminReport
}



Sample Email to the user.

Sample of Admin Report

Updated on May 1, 2012

Added feature to sort Admin report by First Name, Last Name, or Password Expiration Date.

Updated on June 21, 2012

Minor code revision to fix logic errors, still debugging/testing.

, ,

62 Comments