PowerShell Script to Automate Employee Offboarding and Access Revocation
An employee's last day ends at 5 PM. Their Active Directory account gets disabled the next morning when IT gets around to it. Their VPN access, shared drive permissions, and Microsoft 365 license stay active for another day, sometimes longer. That gap is a real security exposure, and it exists almost entirely because offboarding is still a manual checklist in most IT departments. A PowerShell script that automates employee offboarding and access revocation closes that gap the moment HR flags a termination.
Onboarding gets most of the automation attention because it's visible—new hires notice a slow laptop setup. Offboarding is invisible until something goes wrong: a disgruntled former employee still has VPN access, or a departed contractor's account gets flagged in a security audit six months later. Automating it isn't just about saving IT time; it's a security control.
Why Manual Offboarding Creates Risk
Manual offboarding depends on someone remembering every system a departing employee had access to. In most organizations, that's Active Directory, Microsoft 365 or Google Workspace, VPN, shared drives, SaaS tools with SSO, and sometimes physical access badges. A checklist helps, but checklists get skipped when IT is busy, and nobody audits "did we actually revoke access" until an incident forces the question.
The other risk is timing. If offboarding happens hours or days after termination instead of immediately, you've created a window where a departing employee—intentionally or not—retains access to systems they shouldn't. For sensitive terminations, that window matters enormously.
PowerShell scripting against Active Directory and Microsoft Graph closes this gap by triggering revocation the moment HR or a manager flags the termination, not whenever IT gets to the ticket.
Building the Offboarding Script
Disabling the Active Directory Account
The core offboarding action is disabling the AD account immediately, rather than deleting it (deletion breaks audit trails and can orphan mailbox data you may need later):
1Import-Module ActiveDirectory23$username = "jsmith"4Disable-ADAccount -Identity $username56# Move to a dedicated OU for terminated employees7Move-ADObject -Identity (Get-ADUser $username).DistinguishedName `8 -TargetPath "OU=Terminated,DC=company,DC=com"910# Reset password to a random, unknown value as a safety net11$randomPassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 20 | ForEach-Object {[char]$_})12Set-ADAccountPassword -Identity $username -NewPassword (ConvertTo-SecureString $randomPassword -AsPlainText -Force)
Moving the disabled account into a "Terminated" OU makes it easy to apply group policy restrictions in bulk and simplifies later cleanup or account deletion after your data retention period passes.
Revoking Microsoft 365 Licenses and Sessions
Disabling the AD account alone doesn't kill active Microsoft 365 sessions—tokens can remain valid until they expire. Use the Microsoft Graph PowerShell SDK to revoke sessions immediately and remove license assignments:
1Connect-MgGraph -Scopes "User.ReadWrite.All"23$user = Get-MgUser -Filter "userPrincipalName eq 'jsmith@company.com'"45# Revoke all active sign-in sessions immediately6Revoke-MgUserSignInSession -UserId $user.Id78# Remove all assigned licenses9$licenses = Get-MgUserLicenseDetail -UserId $user.Id10Set-MgUserLicense -UserId $user.Id -RemoveLicenses $licenses.SkuId -AddLicenses @()
Revoking sign-in sessions is the step most manual offboarding checklists miss—without it, an active browser session can keep working for hours after the account is technically "disabled."
Removing Group Memberships and Shared Access
Departing employees often retain access through group memberships that outlive the account disable step, especially for shared mailboxes, Teams channels, and distribution lists:
1$groups = Get-ADPrincipalGroupMembership -Identity $username | Where-Object { $_.Name -ne "Domain Users" }23foreach ($group in $groups) {4 Remove-ADGroupMember -Identity $group -Members $username -Confirm:$false5}
Log every group the user was removed from—this list is valuable both for security audits and for understanding what access a role actually required, which helps refine future onboarding templates.
Archiving Mailbox and OneDrive Data
Before wiping anything, archive data that the business may need for legal, compliance, or continuity reasons:
1# Convert mailbox to shared mailbox to preserve email without a license2Set-Mailbox -Identity $username -Type Shared34# Grant the departing employee's manager access to review OneDrive files5Set-SPOUser -Site "https://company-my.sharepoint.com/personal/jsmith" -LoginName "manager@company.com" -IsSiteCollectionAdmin $true
Building an End-to-End Offboarding Workflow
Triggering the Script from HR Systems
The real power of this automation comes from triggering it automatically rather than running it manually. Most HRIS platforms (BambooHR, Workday, Rippling) support webhooks or scheduled exports. Have HR update a termination date field, and use a scheduled PowerShell job or a Power Automate flow to call this script the moment that field changes—see our guide on automating employee onboarding with Power Automate for a similar trigger pattern applied in reverse.
Notification and Audit Logging
Every offboarding run should notify IT security and generate a log entry, so there's a record independent of the HR system:
1$logEntry = [PSCustomObject]@{2 Username = $username3 OffboardedAt = Get-Date4 ActionsCompleted = "AD Disabled, Sessions Revoked, Licenses Removed, Groups Removed"5}6$logEntry | Export-Csv -Path "\\fileserver\logs\offboarding_log.csv" -Append -NoTypeInformation
Handling Shared and Delegated Mailboxes
Many departing employees have access to shared mailboxes or delegated calendars beyond their own account. Query for any shared mailbox permissions the departing user held and remove them explicitly, since these often don't get cleaned up automatically when the primary account is disabled:
1$sharedMailboxes = Get-Mailbox -RecipientTypeDetails SharedMailbox |2 Where-Object { (Get-MailboxPermission -Identity $_.Identity).User -contains $username }34foreach ($mailbox in $sharedMailboxes) {5 Remove-MailboxPermission -Identity $mailbox.Identity -User $username -AccessRights FullAccess -Confirm:$false6}
Coordinating Offboarding with Physical Access Systems
If your building uses badge-based access control, include an API call or scheduled export step that deactivates the departing employee's badge at the same time as their digital accounts, especially for roles with after-hours facility access. Many badge systems (Kisi, Brivo, HID) expose REST APIs that PowerShell can call using Invoke-RestMethod, letting you fold physical security into the same automated offboarding trigger rather than leaving it as a separate manual step for facilities staff.
Best Practices / Pro Tips
Build the script idempotently—running it twice on the same account shouldn't error out or duplicate actions. Check current state (is the account already disabled? are licenses already removed?) before attempting each action.
Separate "immediate revocation" actions (disable account, revoke sessions, remove licenses) from "delayed cleanup" actions (permanent deletion, mailbox conversion cleanup) using a scheduled follow-up task 30 or 90 days later, aligned with your data retention policy.
Test the full script against a dummy test account before wiring it into any automated trigger. Offboarding automation that fires incorrectly against an active employee is far worse than a slow manual process.
Conclusion
Automating employee offboarding with PowerShell closes the single biggest gap in most companies' access management: the delay between termination and revocation. By scripting AD account disabling, Microsoft 365 session revocation, license removal, and group cleanup into one triggered workflow, you turn a security risk into an immediate, auditable, repeatable process.
Start by scripting the core AD and Microsoft 365 revocation steps, test thoroughly against dummy accounts, then connect it to your HR system's termination trigger so access disappears the moment it should—not whenever IT has time to work through a ticket queue.
Frequently Asked Questions
Should I disable or delete an Active Directory account during offboarding?
Disable, not delete, in almost all cases. Deleting immediately breaks Exchange mailbox associations, orphans SID references in permissions, and removes your ability to audit historical access. Move disabled accounts to a dedicated OU and schedule deletion after your retention policy period passes.
How do I handle offboarding for employees with local admin rights on their laptop?
Include a device-level step using Intune or your endpoint management tool to remotely wipe or lock the device as part of the same workflow, triggered alongside the AD and Microsoft 365 revocation steps for a complete offboarding process.
What about SaaS tools that aren't connected to Active Directory or SSO?
For tools without SSO, maintain a master access inventory per employee (updated during onboarding) so offboarding scripts—or a manual checklist for these specific tools—know exactly which non-SSO accounts need manual revocation.
How quickly should offboarding automation run after a termination is flagged?
Immediately for standard terminations, and instantly for involuntary or high-risk terminations. The whole point of automating this process is removing the lag between "employee is no longer authorized" and "employee's access is actually revoked."
How do I handle contractors or temporary staff who aren't in the same HRIS as full-time employees?
Maintain a separate offboarding trigger source for contractor management systems or a simple SharePoint list tracking contract end dates, feeding into the same PowerShell offboarding script. The revocation logic stays identical—only the trigger source and account type change.
Related articles: Automate Employee Onboarding with Power Automate, PowerShell Active Directory Automation Guide, PowerShell Bulk AD User Creation from CSV
Sponsored Content
Interested in advertising? Reach automation professionals through our platform.