Skip to content

Instantly share code, notes, and snippets.

@adamcybersec
Created September 7, 2022 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcybersec/142a1b43621d14c59098af7dae0a932d to your computer and use it in GitHub Desktop.
Save adamcybersec/142a1b43621d14c59098af7dae0a932d to your computer and use it in GitHub Desktop.
#
# README
#
# Open the Azure Cloud Shell
# Run Connect-AzureAD
# Authenticate if needed
# Confirm that all your groups are listed in the $AllGroups var
# Upload add-to-groups.ps1 if needed
# Run ./add-user-to-ad-groups.ps1 "newuser@ourdomain.com.au"
# Review the console outputs and carry on with your day
#
# Parameters
#
param(
# The user email to add to groups
[Parameter(Mandatory=$true)]
[string]
$NewUserEmail
)
$AllGroups = $(
"my-group",
"my-other-group"
)
function Add-NewUserToGroups {
param (
$NewUserId
)
Write-Output "Recieved ObjectId $NewUserId for UPN $NewUserEmail"
foreach ($Group in $AllGroups) {
# Get the Groups ObjectId
$GroupId = Get-AzureADGroup -Filter "DisplayName eq '$Group'" | Select -ExpandProperty ObjectId
# Check if the User is already a Member
$GroupMembers = @(Get-AzureADGroupMember -ObjectId $GroupId -All $true)
# If the User is already a Group Member, tell us and continue the loop
if ($IsUserInGroup = $GroupMembers.ObjectId -contains $NewUserId) {
Write-Output "User $NewUserEmail is already a Member of $Group!"
}
# If the User is not already a Member, add them
else {
Write-Output "Adding $NewUserEmail to $Group"
Add-AzureADGroupMember -ObjectId $GroupId -RefObjectId $NewUserId
}
}
}
# Get the Users ObjectId
$NewUserId = Get-AzureADUser -Filter "UserPrincipalName eq '$NewUserEmail'" | Select -ExpandProperty ObjectId
# Run the main function, pass in the Users ObjectId as a param
Add-NewUserToGroups $NewUserId
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment