Created
September 7, 2022 02:53
-
-
Save adamcybersec/142a1b43621d14c59098af7dae0a932d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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 "[email protected]" | |
# 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