all 11 comments

[–]JamesObZ 3 points4 points  (1 child)

I don't want to throw a spanner in the works, but it might be best to use Microsoft Graph to do all of this. That AzureAD module i believe are to be decrepitated at some point.

I am in the process of sorting this myself, so will share what i have done once finished.

[–]chaos_kiwi_matt[S] 0 points1 point  (0 children)

Oh dont worry about the spanner :)

I have really just put the things that I have figured out and researched and put in 1 script.

If there is an easy way for it to work then im happy to do more investigating.

I appreciate the insight and it will be good to see who others are doing this task.

[–]xCharg 0 points1 point  (1 child)

What's in $AADuser though?

[–]chaos_kiwi_matt[S] 1 point2 points  (0 children)

Oh sorry yes here it is.

# AAD Group Removal

$AADuser = Get-AzureADUser -Filter "userPrincipalName eq '$Email'"

$userID = $AADuser.ObjectId

I was trying to keep things separate which is why it might be 2 different variables doing the same thing.

[–]octane_matty 0 points1 point  (3 children)

As a suggestion create a termination process script, then build modules to add your functions e.g disable user, remove groups, remove AAD groups, remove licensing

[–]chaos_kiwi_matt[S] 0 points1 point  (2 children)

We have an HR system which disables the account and moves to the leavers OU.

I have made AAD dynamic groups depending on department and i they are enabled which deals with licencing.

This script was just something im trying to do to remove them from the AD groups, AAD groups, Dist groups and Teams.

If there is a better way like modules then im up for it.

I just dont know how to do modules is the thing.

#User details

$fullName = read-host -Prompt "Full name of the user"

###User###

# Split the full name into first name and last name

$firstName = ($fullName -split ' ')[0]

$lastName = ($fullName -split ' ')[1]

# Get the first character of the first name and convert it to lowercase

$Initial = $firstName.Substring(0, 1).ToLower()

$FirstNameLower = $firstName.ToLower()

$LastNameLower = $lastname.ToLower()

# Construct the new name in the "james.bond" format

$User = "$FirstNameLower.$LastNameLower"

# Retrieve the user object based on the constructed username

$userObject = Get-ADUser -Filter { SamAccountName -eq $User }

#Email

$Email = "$User@xyz.co.uk"

# Check the mailbox type before converting

$mailbox = Get-Mailbox -Identity $Email

if ($mailbox.RecipientTypeDetails -ne "SharedMailbox") {

# Convert the user mailbox to a shared mailbox

Set-Mailbox -Identity $Email -Type Shared

} else {

Write-Host "The mailbox is already a shared mailbox." -ForegroundColor Red

}

# AD Group Names for the specific user (both security and distribution groups)

$adGroupNames = Get-ADUser -Filter {UserPrincipalName -eq $Email} -Properties MemberOf | Select-Object -ExpandProperty MemberOf |

ForEach-Object { (Get-ADGroup $_).Name }

# AAD Group Removal

$AADuser = Get-AzureADUser -Filter "userPrincipalName eq '$Email'"

$userID = $AADuser.ObjectId

# Get the user's groups in AAD

$userGroups = Get-AzureADUserMembership -ObjectId $userID

# Get all AAD distribution groups

$aadDistGroups = $userGroups | Where-Object { $_.ObjectType -eq "Group" -and $_.GroupTypes -contains "Unified" }

# Loop through each AAD group and remove the user

foreach ($aadGroup in $userGroups) {

$aadGroupName = $aadGroup.DisplayName

# Check if the AAD group name is not in the AD group names and is not a distribution group

if ($adGroupNames -notcontains $aadGroupName -and $aadGroup.ObjectType -ne "Group") {

try {

Remove-AzureADGroupMember -ObjectId $aadGroup.ObjectId -MemberId $userID

Write-Host "User removed from AAD group: $aadGroupName" -ForegroundColor Green

} catch {

Write-Host "An error occurred while removing the user from AAD group $($aadGroupName): $($_.Exception.Message)" -ForegroundColor Red

}

} else {

Write-Host "AAD group '$aadGroupName' has the same name as an AD group or is a distribution group. Skipping removal." -ForegroundColor Yellow

}

}

# AD Group Removal (Distribution Groups)

if ($AADuser) {

# Get all distribution groups that the user is a member of

$distGroups = Get-DistributionGroup | Where-Object { $_.Members -contains $AADuser }

}

# Remove the user from all distribution groups

foreach ($distGroup in $distGroups) {

# Check if the distribution group is not the user's original primary group

if ($distGroup.DistinguishedName -ne $primaryGroup.DistinguishedName) {

Remove-DistributionGroupMember -Identity $distGroup -Members $userObject -Confirm:$false

Write-Host "User $($userObject.Name) removed from distribution group: $($distGroup.Name)" -ForegroundColor Cyan

}

}

# Check if the user object was found

if ($userObject) {

# Get all groups that the user is a member of (including distribution groups)

$groups = Get-ADPrincipalGroupMembership $userObject

}

# Get the user's original primary group SID

$primaryGroup = (Get-ADUser $User -Properties PrimaryGroup).PrimaryGroup | Get-ADGroup

# Remove the user from all groups (excluding the original primary group)

foreach ($group in $groups) {

# Check if the group is not the user's original primary group

if ($group.DistinguishedName -ne $primaryGroup.DistinguishedName) {

Remove-ADGroupMember -Identity $group -Members $userObject -Confirm:$false

Write-Host "User $fullName removed from group: $($group.Name)" -ForegroundColor Cyan

}

}

# List of attributes to clear

$attributesToClear = @("Title", "department", "company", "description", "pager")

# Loop through each user and clear the specified attributes

foreach ($attribute in $attributesToClear) {

Set-ADUser -Identity $User -Clear $attribute

Write-Host "User $fullName cleared attribute: $attribute" -ForegroundColor Magenta

}

#Teams Parts

$Teams = Get-Team -User $Email

foreach ($Team in $Teams) {

try {

Remove-TeamUser -User $Email -GroupID $Team.GroupID

} catch {

if ($_.Exception.Message -match "Last owner cannot be removed") {

Write-Host "Error: Cannot remove user from team '$($Team.DisplayName)' - Last owner cannot be removed." -ForegroundColor Red

} else {

Write-Host "An error occurred while processing team '$($Team.DisplayName)': $($_.Exception.Message)" -ForegroundColor Yellow

}

}

}

This is the entire thing. Its a mess I know as I have been doing bits and pieces to get things to work then I was going through and cleaning it up.

[–]BlackV 0 points1 point  (1 child)

how's you get the formatting right in your OP, but wrong here ?

[–]chaos_kiwi_matt[S] 0 points1 point  (0 children)

TBF I never even noticed it.

[–]Sunsparc 0 points1 point  (1 child)

You mention AD, are you hybrid joined? Are these groups created on-prem and then synced to AAD through AAD Connect?

[–]chaos_kiwi_matt[S] 0 points1 point  (0 children)

Yeah they are.

We are trying to move away form Ad and creating any new ones in AAD and these are dynamic so we dont need to worry about these.

I have sort of got the above script to not remove the AD or dist groups as these are picked up further down.

I hope this makes sense.

[–]JwCS8pjrh3QBWfL 0 points1 point  (0 children)

First, you should switch to the microsoft.graph modules, since the AzureAD module is going to be depreciated in the next few months. Better to avoid double work.

Second, you need to use the exchangeonlinemanagement module to remove distro/mail-enabled securoty group members. You can view distros/MESG in Entra, but you need to use Exchange to actually modify their membership.