Categories
Auditing Powershell

Auditing: Notify Manager Of Contractor Account Expiry

Notify manager of contractor Active Directory user account expiry via email and notify the service desk of any incomplete user accounts.

I personally think that notifying employees/managers of accounts that are due to expire creates a better customer experience than that employee/contractor coming in one day and not being able to log in.

With this in mind I have created the below script that works in two parts by looking for the string Contractor in the EmployeeType attribute.

Part 1 is gathering all the direct reports for a manager and if the conditions are met they will receive one email with any employees whose accounts are due to expire in the next 30 days.

Part 2 Gathers all users who have the EmployeeType set but are missing details such as account expiry or manager.

The script below provides basic output to the console and if you uncomment the send mail section it will then send the email. I have only included very basic email output but you can wrap your own HTML email template around these to make them look much more professional.


### Getting all users and their direct reports
Get-ADUser -Filter * -Properties DirectReports,EmailAddress | ForEach {
### Setting up array to be sent to the manager if criteria is met
    $CompleteUsersResults = @()
### For each user that has direct reports it then continues to examine those reports
    If ($_.DirectReports) {
### Sets up variables containing the managers name and email address to send the email
        $CompleteUsersManagerEmailAddress = $_.EmailAddress
        $CompleteUsersManagersName = $_.Name
### Examines each direct report for matching criteria. 
        $_.DirectReports | ForEach {
### Gets user details for each direct report 
            $CompleteUserDetails = Get-ADUser $_ -Properties AccountExpirationDate,EmployeeType,Enabled
### Excludes those direct reports with no expiry date set
             If( ($CompleteUserDetails.AccountExpires -eq 0) -or 
                 ($CompleteUserDetails.AccountExpires -eq 9223372036854775807 )) {
### Cancels the sending of any email for those with no expiry date                
                $SendEmail = $false                
            }
### If a user has an expiry date it continues to do further checks
            If ( $CompleteUserDetails.AccountExpirationDate ) {
### This checks if the user
### Has the EmployeeType attribute completed with the word Contractor
### The account is due to expire in the next 30 days 
### The account is due to expire after todays date
### The account is enabled.
                If ( ($CompleteUserDetails.AccountExpirationDate -lt (Get-Date).AddDays(30)) -and 
                     ( $CompleteUserDetails.AccountExpirationDate -gt (Get-Date)) -and
                     ( $CompleteUserDetails.Employeetype -eq 'Contractor') -and 
                     ( $CompleteUserDetails.Enabled -eq $True)) {
### If the above criteria is met the Send Email flag is set to true
                    $SendEmail = $True
### This sets up variables to obatin the expiring users name and the expiry date
                    $CompleteUsersName = $CompleteUserDetails | Select-Object SamAccountName -ExpandProperty SamAccountName
                    $CompleteExpiryDate = $CompleteUserDetails | Select-Object AccountExpirationDate -ExpandProperty AccountExpirationDate
### This creates a new PS Object to store the users name and expiry date
                    $Properties = [ordered]@{
                       "Username  " = $CompleteUsersName
                       
                        "  Account Expiration Date   " = $CompleteExpiryDate
                    }
### This adds the PS Object to an array that will be sent to the manager
                   $CompleteUsersResults += New-Object PsObject -Property $Properties

                   
                }
            }

        }

    }
### If the above criteria is met this is where it begins sending the email
    If ($SendEmail -eq $True) {
### This displays who will be emailed in the console
Write-host ""
Write-Host "Emailing Manager - $CompleteUsersManagersName"
Write-Host $CompleteUsersManagerEmailAddress 
           $CompleteUsersResults | Format-Table
### This converts the array with the user details in to an HTML fragment to be inserted in to the HTML email layout below  
       $CompleteUsersResults = $CompleteUsersResults | ConvertTo-Html -Fragment

### This send the email using the above HTML
    Send-MailMessage -From 'email@domain.com' -To $CompleteUsersManagerEmailAddress -Subject 'Account Expiration Report' -Body "$CompleteUsersResults" -SmtpServer 'SMTP Server' -BodyAsHtml
    }
### This is the else telling it not to send email if the criteria was not met
   $sendEmail = $false 

}

### This is where it inspects those users where there is missing information such as:
### EmployeeType attribute is set to contractor
### No manager specified /or/
### No expiriation date / and /
### User account is enabled
$UsersMissingDetails = @(Get-ADUser -Filter {Employeetype -eq 'contractor'} -Properties Manager,AccountExpirationDate,EmployeeType,Enabled | 
Where-Object {(($_.Manager -like $Null) -or 
    ($_.AccountExpirationDate -eq $Null) -and 
    ($_.Enabled -eq $True))}) | 
    Select-Object @{label='Name';expression={$_.Name}},
    @{label='User Name';expression={$_.SamAccountName}},
    @{label='Account Expires';expression={$_.AccountExpirationDate}},
    @{label='Manager';Expression={$_.manager -replace '^CN=|,.*$'}} 
### This checks to see if any incomplete users need to be sent to the service desk for updating  
  if ($UsersMissingDetails -ne $null){
### This writes the results to be emailed out to the console. 
  write-host "Sending Email To Service Desk"
  $UsersMissingDetails
  $UsersMissingDetails = $UsersMissingDetails  | ConvertTo-Html -Fragment
### This is setting up the same HTML email format as above with slightly different wording
     
### This send the email using the above HTML
Send-MailMessage -From 'email@domain.com' -To 'to mail' -Subject 'Contractors Missing Details Report' -Body "$UsersMissingDetails" -SmtpServer 'SMTP Server' -BodyAsHtml 
}
else{}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.