Safe PowerShell onboarding and offboarding
Write idempotent onboarding and offboarding scripts with a dry-run plan, approval and rollback inventory.
By Invicly Tech, , in Microsoft Entra & Microsoft 365 Administration. About 11 minutes to read.
In short
Onboarding and offboarding scripts touch real accounts, so they must be safe to run twice, show their plan before acting and leave a record of what changed. Microsoft Graph PowerShell plus the built-in ShouldProcess support gives you a -WhatIf dry run, a confirmation prompt and a natural place to write a rollback inventory.
Think of it like this: It is like a surgeon's checklist: confirm the patient, mark the site, get a second signature, and note every instrument used so the count can be checked afterwards.
Explained simply
When someone joins, an admin creates their account, adds groups, gives licences and sets up mail. When they leave, the admin does the reverse. Doing this by hand is slow and easy to get wrong, so many teams use a PowerShell script. A script repeats mistakes as fast as it repeats good work, though, so it must be built carefully.
Safe scripts follow a few rules. They connect with only the permissions they need. Each step checks the current state before changing it, so running the script twice does no harm. This property is called idempotency.
Before changing anything, the script prints a plan: what it would create, add or remove. PowerShell has this built in. If your function declares SupportsShouldProcess, you can run it with -WhatIf to see the plan, or -Confirm to be asked before each change.
A second person reads the plan and approves it. Then the script runs for real and writes a rollback inventory: a file listing each change, what was there before, and the command that undoes it. If something goes wrong, you can reverse exactly what happened.
Practise in a lab or trial tenant with fake users such as ada.test@contoso.example. If you have no tenant, run the same logic against a JSON file of mock users and groups; the planning and inventory parts work the same way.
Press Play on a diagram to walk through it one step at a time.
- 1Read input
CSV row or ticket for one person
- 2Read current state
Look up user, groups and licences
- 3Plan
List only the differences
- 4Approve
A second person checks the -WhatIf plan
- 5Apply
Run each step through ShouldProcess
- 6Record
Write before and after values to an inventory
- Requester to Script: Run with -WhatIf for HR ticket 10421Run with -WhatIf for HR ticket 1042
- Script to Graph: Read current user, groups and licences2Read current user, groups and licences
- Script to Requester: Plan: 1 user, 3 groups, 0 removals3Plan: 1 user, 3 groups, 0 removals
- Requester to Approver: Attach plan to ticket for review4Attach plan to ticket for review
- Approver to Script: Approved: run for real5Approved: run for real
- Script to Graph: Apply changes via ShouldProcess6Apply changes via ShouldProcess
- Script to Approver: Rollback inventory saved to ticket7Rollback inventory saved to ticket
In depth
Connect with least scopes
Write down the operations first, then choose scopes. Creating users and setting properties needs User.ReadWrite.All. Adding group members needs GroupMember.ReadWrite.All. Assigning a licence directly needs User.ReadWrite.All or LicenseAssignment.ReadWrite.All, but group-based licensing means you only change group membership. Revoking sessions needs User.RevokeSessions.All or User.ReadWrite.All.
The signed-in admin also needs a matching role, such as User Administrator plus Groups Administrator, ideally activated through PIM for the session. After connecting, check (Get-MgContext).Scopes and stop the script if anything extra or missing appears. Disconnect at the end so the token does not linger in the session.
- Onboard: User.ReadWrite.All, GroupMember.ReadWrite.All
- Offboard: add User.RevokeSessions.All
- Prefer group-based licensing over direct assignment
- Fail fast if scopes differ from the plan
Making each step idempotent
An idempotent step reads, compares and only then writes. For a new user, look up the UPN first; if it exists, compare its properties and update only what differs. For group membership, read the members and skip users already present. For removal, skip if the user is already gone.
Also decide what counts as the same object. Use a stable key such as employeeId rather than the display name, because names change. Make the script stop on unexpected states, for example two accounts with the same employeeId, instead of guessing. A re-run after a failure should continue from where it stopped and finish with the same end state.
- Read, compare, then write
- Match on a stable key such as employeeId
- Stop on ambiguity; do not guess
- Re-runs finish the job without duplicates
- 1Desired state
From the HR row or ticket
- 2Read actual state
Query Graph
- 3Compare
Find the difference, if any
- 4Apply difference
Through ShouldProcess
- 5Verify
Read again and confirm
- Back to step 1
Dry runs with ShouldProcess
Add [CmdletBinding(SupportsShouldProcess)] to an advanced function and wrap each change in if ($PSCmdlet.ShouldProcess(target, action)). Running with -WhatIf prints lines like What if: Performing the operation "add user" on target "group Sales" and changes nothing. Running with -Confirm asks before each change.
Set ConfirmImpact to High on destructive actions such as disabling or deleting an account; PowerShell then prompts automatically when $ConfirmPreference is at its default of High. -WhatIf flows down to cmdlets that support it, but Graph SDK cmdlets do not all honour -WhatIf themselves, so always guard the Graph call with your own ShouldProcess check. For approvals, capture the -WhatIf output to a file and attach it to the ticket.
- -WhatIf: show plan, change nothing
- -Confirm: prompt per change
- ConfirmImpact High for disable or delete
- Guard every Graph write with ShouldProcess
Approval and the rollback inventory
Approval works best on evidence, not trust. The requester runs the dry run, saves the plan and a second admin compares it with the HR request. Only then is the real run allowed, ideally by a different person or by a pipeline that requires an approver.
During the real run, append one row per change to a CSV or JSON file: time, operator, object ID, action, value before, value after and the undo command. Store it with the ticket. For offboarding, the inventory also lists group memberships, licences, mailbox delegates and owned Teams, so an accidental leaver can be restored quickly within the 30-day soft-delete window.
- Plan file attached to the ticket
- Second person approves
- One inventory row per change
- Include the undo command
A safe offboarding order
Order matters because some steps are hard to reverse. A safe sequence is: block sign-in (AccountEnabled false), revoke sessions, record and remove group memberships, hand mail and files to the manager, then remove licences once data is handled. Delete the account last, after the retention period your policy sets.
Revoke-MgUserSignInSession invalidates refresh tokens, but access tokens already issued can stay valid until they expire, by default 60 to 90 minutes, unless the app supports continuous access evaluation. Mail handover is done in Exchange Online, for example converting the mailbox to a shared mailbox with Set-Mailbox -Type Shared from the ExchangeOnlineManagement module before removing the licence.
- Block, revoke, record, hand over, unlicense, delete
- Revocation is not instant for issued access tokens
- Convert mailbox before removing the licence
- Soft-deleted users can be restored for 30 days
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Connect with least scopes~40m
- 2Make each step idempotent~40m
- 3Print a dry-run plan~40m
- 4Require approval~40m
- 5Record a rollback inventory~40m
Key points
- Connect with the fewest scopes the run needs and check them with Get-MgContext.
- Idempotent means check first, then act: adding a member who is already in the group should be a no-op, not an error.
- Add [CmdletBinding(SupportsShouldProcess)] so -WhatIf and -Confirm work for free.
- Approval should happen on the dry-run output, not on the script source.
- Write a rollback inventory (what was there before, what you changed) as you go, not afterwards.
Key terms
Tap a card to flip it. 0/5 known
Examples
function Add-IvGroupMember {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
param([string]$UserId, [string]$GroupId)
$current = Get-MgGroupMember -GroupId $GroupId -All | Select-Object -ExpandProperty Id
if ($UserId -in $current) { Write-Verbose 'Already a member'; return }
if ($PSCmdlet.ShouldProcess("group $GroupId", "add user $UserId")) {
New-MgGroupMember -GroupId $GroupId -DirectoryObjectId $UserId
[pscustomobject]@{ Action='AddMember'; UserId=$UserId; GroupId=$GroupId; Undo='Remove-MgGroupMemberByRef' }
}
}
# Dry run first: Add-IvGroupMember -UserId $u -GroupId $g -WhatIfCheck, then act; -WhatIf prints the plan and the returned object feeds the rollback inventory.
Onboarding plan from a CSV row
Input is a CSV row with employeeId, name, department and UPN. The function looks up the user by employeeId and creates them only if missing. Run it with -WhatIf first; the output is the plan an approver reviews. Cleanup in the lab: Remove-MgUser on the test object.
function New-IvUser {
[CmdletBinding(SupportsShouldProcess)]
param([pscustomobject]$Row)
$existing = Get-MgUser -Filter "employeeId eq '$($Row.EmployeeId)'" -ConsistencyLevel eventual -CountVariable c
if ($existing) { Write-Verbose "$($Row.Upn) exists"; return $existing }
if ($PSCmdlet.ShouldProcess($Row.Upn, 'create user')) {
New-MgUser -AccountEnabled -DisplayName $Row.Name -MailNickname $Row.Alias `
-UserPrincipalName $Row.Upn -EmployeeId $Row.EmployeeId -Department $Row.Dept `
-PasswordProfile @{ ForceChangePasswordNextSignIn = $true; Password = $Row.TempPassword }
}
}
Import-Csv .\joiners.csv | ForEach-Object { New-IvUser -Row $_ -WhatIf }Offboarding with a rollback inventory
The function records memberships before removing them, disables sign-in and revokes sessions. ConfirmImpact High makes PowerShell prompt by default. Expected evidence: a JSON file with prior groups and the undo commands, and the user showing AccountEnabled false.
function Disable-IvLeaver {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param([string]$UserId)
$groups = Get-MgUserMemberOf -UserId $UserId -All |
Where-Object { $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.group' }
$inv = [ordered]@{ UserId=$UserId; At=(Get-Date).ToString('o'); By=(Get-MgContext).Account;
Groups=$groups.Id; Undo='Update-MgUser -AccountEnabled:$true; re-add Groups' }
if ($PSCmdlet.ShouldProcess($UserId, 'block sign-in, revoke sessions, remove groups')) {
$inv | ConvertTo-Json | Set-Content ".\inventory-$UserId.json"
Update-MgUser -UserId $UserId -AccountEnabled:$false
Revoke-MgUserSignInSession -UserId $UserId | Out-Null
$groups | ForEach-Object { Remove-MgGroupMemberByRef -GroupId $_.Id -DirectoryObjectId $UserId }
}
}Quick reference
- [CmdletBinding(SupportsShouldProcess)] gives your function -WhatIf and -Confirm.
- if ($PSCmdlet.ShouldProcess($target, $action)) { ... } wraps every write.
- ConfirmImpact = 'High' prompts by default for destructive steps.
- Update-MgUser -UserId $id -AccountEnabled:$false blocks sign-in.
- Revoke-MgUserSignInSession -UserId $id invalidates refresh tokens.
- Remove-MgGroupMemberByRef -GroupId $g -DirectoryObjectId $u removes a member.
- Match people on employeeId, not display name.
- Inventory row: time, operator, object, action, before, after, undo.
Common mistakes
- Calling New-MgGroupMember blindly, so a re-run fails halfway and leaves the person partly onboarded.
- Deleting the user as the first offboarding step, which loses the easy undo and starts the 30-day soft-delete clock early.
- Running with a Global Administrator session for convenience instead of the scopes the task needs.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Turn a plain function that adds a user to a group into one that supports -WhatIf.
- Exercise 2medium
Without a tenant, write a dry-run planner that compares a desired group list with a mock current state in JSON and prints adds and removes.
- Exercise 3hard
Write the restore steps for an offboarded user from the inventory JSON in example two, and say what cannot be restored by the script.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do Microsoft Graph cmdlets support -WhatIf on their own?
- Not reliably. Wrap each Graph write in your own ShouldProcess check so -WhatIf always works.
- Should I delete leavers straight away?
- Usually not. Block sign-in, hand over data and keep the account for your retention period. Deleted users can only be restored for 30 days.
- Where should the script run from?
- From a managed admin workstation or a pipeline with an approval step, using a signed script and a certificate-based app for unattended runs.
- Can I practise without a Microsoft 365 tenant?
- Yes. Put mock users and groups in JSON files and point your planner at them. The compare, plan and inventory logic is the same; only the read and write calls differ.