I wrote this script to help streamline the process of terminating an employee at work. I’m still certainly learning Powershell, but this definitely scratched an itch at $job.

The only thing you will need to change to run it is the path to the OU. You will also need a Log folder on your C: drive – this is where the list of groups will get dumped to with the username as the filename. We occasionally have rehires, so it’s nice to have a list of what groups they were in prior to being terminated in case they come back.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<#
.NOTES
===========================================================================
Created on: 3/21/2014 9:38 AM
Created by: Cole Lavallee
Filename: TermUser.ps1
===========================================================================
.DESCRIPTION
A description of the file.
#>

Import-Module ActiveDirectory
$OU = "OU=Terminated Users,DC=company,DC=com"
$date = Get-Date -format d
$ErrorActionPreference= 'silentlycontinue'
# Get User Name
$user = Read-Host 'Enter Username'

$username = Get-ADUser $user

#Disable Account
Disable-ADAccount -Identity $user

#Set Account Expiration and update Description
Set-ADUser -Identity $user -AccountExpirationDate (get-date).AddDays(1) -Description "Locked on $date"

#Get a list of group membership

Get-ADUser -Identity $user -Properties memberof | select -ExpandProperty memberof | Out-File C:Log$user.txt

# Remove all group memberships (will leave Domain Users as this is NOT in the MemberOf property returned by Get-ADUser. Surpresses the need to confirm removal and error when attempting to remove the Domain Users group.)
Get-ADPrincipalGroupMembership -Identity $user | % {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false $ErrorActionPreference}

#Move user to the Terminated User
Move-ADObject $username -TargetPath $OU