Script Repository


Users whose accounts will expire within 30 days

January 11, 2017
1368

This script generates and emails an HTML-formatted report containing user accounts from all domains managed by Adaxes that will expire within 30 days.

To generate the reports upon request, you can create a Custom Command that runs the script. To schedule the report, you need to create a Scheduled Task configured for the Domain-DNS object type and run it against any of your AD domains.

To add the script to a Custom Command or Scheduled Task, use the Run a program or PowerShell script action.

Parameters:

  • $numDays - specifies the number of days left until expiration of those user accounts that will be included in the report;
  • $to - specifies email addresses of the recipient(s) of the report;
  • $subject - specifies the email message subject;
  • $reportHeader - specifies the email message header;
  • $reportFooter - specifies the email message footer.
Edit Remove
PowerShell
$numDays = 30 # TODO: modify me
 
# Email message settings
$to = "recipient@domain.com" # TODO: modify me
$subject = "Users whose accounts will expire within $numDays"
$reportHeader = @"
<h3><b>Users whose accounts will within $numDays days</b></h3><br/>
<table border="1">
    <tr>
        <th>Full name</th>
        <th>Logon name</th>
        <th>Account Expiration Date</th>
    </tr>
"@
 
$reportFooter = @"
</table><br/>

<p><i>Please do not reply to this e-mail, it has been sent to you for notification purposes only.</i></p>
"@
 
$accountExpiresDate = ((Get-Date).AddDays($numDays)).ToFileTime()
$currentDate = (Get-Date).ToFileTime()
 
# Search users
$searcher = $Context.BindToObject("Adaxes://rootDSE")
$searcher.PageSize = 500
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.SearchFilter = "(&(sAMAccountType=805306368)(accountExpires>=$currentDate)(accountExpires<=$accountExpiresDate))"
$searcher.SetPropertiesToLoad(@("cn", "userPrincipalName", "accountExpires"))
$searcher.VirtualRoot = $True
try
{
    $searchResult = $searcher.ExecuteSearch()
    $users = $searchResult.FetchAll()
   
    if ($users.Count -eq 0)
    {
        return
    }
   
    # Include users to expire in the report
    foreach ($userID in $users)
    {
        # Add user information to report
        $reportHeader += "<tr><td>" + $userID.Properties["cn"].Value + "</td>"
        $reportHeader += "<td>" + $userID.Properties["userPrincipalName"].Value + "</td>"
        $accountExpires = [DateTime]::FromFiletime([Int64]::Parse($userID.Properties["accountExpires"].Value))
        $reportHeader += "<td>" + $accountExpires.ToString("yyyy-MM-dd") + "</td></tr>"
    }
}
finally
{
    # Release resources used by AD search
	$searchResult.Dispose()
}

# Build email message body
$report = $reportHeader + $reportFooter
 
# Send mail to the initiator
$Context.SendMail($to, $subject, $NULL, $report)


Comments ( 0 )
No results found.
Leave a comment