Sheridan Wendt
  • Home
  • Technology
  • Business
  • Music
  • Adventures
  • Resume
  • Contact

Technology

Off-boarding (Terminating) Users with PowerSHell

9/1/2017

Comments

 
Terminating other employees isn't fun for anyone. First is there is a personal aspect if  you know the person that is being terminated. Next there are a lot of steps involved. The termination process must be done carefully, according to procedure, and there often has to be a trail that is able to be audited for legal and compliance reasons. ​Let's automate it!
View the full .ps1 file on github:
TerminateUser.ps1
Disclaimer: Each organization has unique needs, unique procedures, and a unique environment. Be sure that you take all of these considerations into account before using this script in your environment.

To help make the process as easy as possible, I use PowerShell. I've written a script that performs the normal steps involved in terminating access for a specific user. I'll explain the logic behind each step throughout this article. The steps include:
  • Disabling the user in Active Directory
  • Setting a random password for the user
  • Exporting a list of group membership for later reference
  • Removing user from all groups for security reasons
  • Archiving user folders
  • Fforwarding future emails to the user’s previous supervisor
  • Disabling ActiveSync in Exchange
  • Removing user’s extension from Active Directory
  • Clean ADUC: Moves the user’s account to a specific OU so ADUC stays nice and clean
  • Bonus: This script will skip users deemed as “Protected Users”, such as user accounts of corporate officers, important services accounts, members of the security team, etc.

Disabling the User: 
When employees leave, it's important to disable their user account as soon as possible to mitigate any risk of an insider threat, or more likely, embarrassing emails being sent. Plenty of funny stories there :) Disabling a user via PowerShell is a pretty straightforward command: 
​#Disable Active Directory account
Disable-ADAccount -Identity $Username -Confirm:$false
Write-Host "User $Username disabled"
Changing the users's password:
This is just an extra security precaution. Yes; it's probably over kill considering their account has been disabled. You can never be too careful. Imagine the user being terminated has a friend in IT and their account is temporarily enabled again as a favor. You'd be surprised how many administrators have not enabled auditing to be able to review changes that are made in Active Directory. Anyways, I always recommend changing the user's password just in case. It's automated, so why not. 
This script generates a random string each time it's run and sets that random string as the user's password. ​
# Generate random string
​
$Random = -join ((65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_})

# Set random password for user
Set-ADAccountPassword -Identity $Username -NewPassword (ConvertTo-SecureString -AsPlainText "P!1$Random" -Force)
Exporting Group Membership:
Sometimes after a user is terminated, it becomes necessary to determine what security and distribution groups the user was in before they were terminated. This is usually only needed to comply with regulatory authorities or for supporting evidence in lawsuits. Either way, having evidence of group membership sometimes comes in handy. This script exports a list of all of the groups the user was a member of and saves them to a log file. ​
​#Export list of groups user is a Member Of
(Get-ADUser $Username).Name | Add-Content $PathLog\$Username.txt
Get-ADPrincipalGroupMembership $Username | Select Name | Add-Content $PathLog\$Username.txt
Write-Host "$Username Groups exported"
​Removing Group Membership:
After exporting a list of groups the user was in, it's important to remove the user from all groups. If the account ever gets enabled again for any reason, it won't have permissions to any of the network locations it may have inherited through groups if it were still in them.
#Remove user from all groups except 'Domain Users'
Get-ADPrincipalGroupMembership -Identity $Username | where {$_.Name -notlike "Domain Users"} |% {Remove-ADPrincipalGroupMembership -Identity $Username -MemberOf $_ -Confirm:$false}
Write-Host "$Username removed from groups"
Archiving user folders:
For some organizations, this step may not be necessary. For those who need to conserve space on expensive storage arrays, archiving user folders when the folders are no longer needed is an easy way to free up space. Home folders or application folders make perfect candidates for this portion of the script. 
#Archive folders to FileServer
Move-Item -path "\\FileServer\Users\$Username" -Destination "\\FileServer\EmployeeArchive\$Username" -force
Write-Host "$Username Home Drive archived to \\FileServer\EmployeeArchive\$Username"
Move-Item -path "\\AppServer\Users\$Username" -Destination "\\FileServer\EmployeeArchive\$Username\AppName" -force
Write-Host "$Username App Drive archived to \\FileServr\EmployeeArchive\$Username\AppName"
Forwarding future emails:
How many sales opportunities are lost because emails are sent to sales representatives who no longer work at your organization? If it's already standard practice in your organization to forward emails of terminated employees to someone who's staying on; that's great! If your organization doesn't, you should seriously consider it. Either way, here's how you automate it if you have Microsoft Exchange on-premise. If you have Office 365, stay tuned for my article on Exchange Online.
#Get supervisor name to forward emails
Function Get-Supervisorname {
$Global:Supervisorname = Read-Host "Enter supervisor / manager username to forward emails to"
if ($Supervisorname -eq $null){
Write-Host "Supervisor name cannot be blank. Please re-enter"
Get-Username
}
$SuperCheck = Get-ADUser $Username
if ($SuperCheck -eq $null){
Write-Host "Invalid username. Please verify this is the logon id for the supervisor"
Get-Username
}
}
Get-Supervisorname
#Get supervisor SMTP address
$SupSMTP = (Get-ADUser $Supervisorname -Properties mail).mail
#Forward mail to supervisor
Set-Mailbox -Identity $Username -ForwardingAddress $SupSMTP
$SupName = (Get-Mailbox -identity $Username).forwardingaddress.name
Write-Host "Forwarding $Username's mail to: $SupName"
Disabling ActiveSync in Exchange On-Premise:
Imagine this; a year after a user has been terminated their mailbox gets enabled by a security administrator to find some old emails. Why? Let's say for an unemployment claim. Now imagine that the user never removed their email account from their mobile device and the password is still the same. Their mobile device would start downloading all of the emails that have been sent to their old email address in the last 12 months as unread mail. Is it overkill? Probably. Is it possible? Sadly, yes. So we have to prevent it. Can't be too careful.
This part of the script prevents IMAP enabled devices, usually a smart phone, from syncing with Exchange. 
#Disable ActiveSync
set-casmailbox -identity $Username -ActiveSyncEnabled $false
$ActiveSync = (Get-casmailbox -identity $Username).activesyncenabled
Write-Host "ActiveSync Enabled: $ActiveSync"
Removing Phone Extension:
If your phone system, or phone call reporting system, uses phone extensions from Active Directory this next part comes in handy. The commands below remove the user's extension from Active Directory so that any calls made after the user has been terminated will not show up as that user in any call reporting systems. 
#Remove phone extension from ipPhone attribute to improve Microcall report accuracy
set-aduser $Username -Replace @{ipPhone=" "}
Clean Active Directory: 
Ever look inside Active Directory and see a user account that doesn't seem to be there for a reason? Definitely not fun. It's best practice to delete user accounts when they are no longer needed, so be sure to consider all of the risks and decide what's best for your organization. Sometimes it is convenient to disable an account for a time, instead of deleting it. This is just in case the account is needed to access folders or files that the account has taken ownership of. In these scenarios, the disabled user accounts should be moved to one Organizational Unit (OU) in Active Directory so that it's easy to keep tabs on them. Stay tuned for a different script that checks for disabled users older than XX days and deletes them once a for all. 
#Move disabled user to Disabled OU in ADUC
Move-ADObject -Identity (Get-ADuser $Username).objectGUID -TargetPath 'OU=Disabled,OU=User,DC=domain,Dc=local'
$UserDisabled2 = (Get-ADUser $Username).Enabled
$UserGroups2 = Get-ADPrincipalGroupMembership $Username | Select Name
$UserOU2 = Get-ADUser $Username | select @{l='Parent';e={([adsi]"LDAP://$($_.DistinguishedName)").Parent}}
$SupName2 = (Get-Mailbox -identity $Username).forwardingaddress.name
$ActiveSync2 = (Get-casmailbox -identity $Username).activesyncenabled
#Create a PST Backup of $Username's Mailbox
Protected Users:
Scripts are dangerous when not used correctly. What if a typo is made and a corporate officer is terminated? You don't want to be the one saying "Uh oh. We didn't think plan ahead for typos boss..." Determine who should be considered a protected user and protect them from accidental, or malicious, termination by preventing their usernames to be input as the user to be terminated. We accomplish that by instructing PowerShell to check the username to be terminated against a predefined list before performing any termination actions. Check it out: 
# Defined protected users. These could be usernames or populated based on job title
$
ProtectedUsers = "CEOuser", "COOuser", "CIOuser", "CISOuser"

​#Get username to terminate and verify username isn't protected
Function Get-Username {
$Global:Username = Read-Host "Enter username to terminate"
if ($Username -eq $null){
Write-Host "Username cannot be blank. Please re-enter username"
Get-Username
}
$UserCheck = Get-ADUser $Username
if ($UserCheck -eq $null){
Write-Host "Invalid username. Please verify this is the logon id / username for the account"
Get-Username}
$Protected = $ProtectedUsers -contains "$Username"
if ($Protected -eq $True){
Write-Host "$Username is a protected user and should not be deleted. See $NetAdmin or $SecMgr for details"
Get-Username}
}
Get-Username
Comments

    Repositories

    PowerShell
    SQL

    Author

    Sheridan's interests are in technology, business, music, and adventures

    View my profile on LinkedIn

    RSS Feed

    Categories

    All
    Alerts
    Azure
    Business Intelligence
    Data Visualization
    Notifications
    Photo Frame
    PowerShell
    Raspberry Pi
    Scripting
    SMS
    SQL
    Technology
    Virtualization
    VMWare

    Business

    Archives

    June 2019
    May 2019
    September 2018
    May 2018
    April 2018
    March 2018
    February 2018
    December 2017
    September 2017
    July 2003

Powered by Create your own unique website with customizable templates.
  • Home
  • Technology
  • Business
  • Music
  • Adventures
  • Resume
  • Contact