I'm automating a task in Active Directory/Azure that checks a hashtable of groups, if they're a member of the key (AAD group) then add them to the value (AD group). The structure and method are basically as follows:
$mappings = @{
"1 - AAD Group" = "AD 1"
"1 - Another Group" = "AD 1"
"2 - Hello" = "AD 2"
"3 - Hi" = "AD 3"
"3 - Another" = "AD 3"
"3 - Again" = "AD 3"
}
foreach ($mapping in $mappings.GetEnumerator() | Sort-Object -Property Key) {
# Get AAD and AD group names
$aadgroup = $mapping.Key
$adgroup = $mapping.Value
# Get object ID of AAD group
$objectid = (Get-AzureADGroup -All $true | Where-Object {$_.DisplayName -eq $aadgroup}).ObjectId
# Get members of AAD group
$members = Get-AzureADGroupMember -All $true -ObjectId $objectid
# Check if each member is part of the corresponding AD group
foreach ($member in $members) {
$username = $member.MailNickName
$groups = (Get-ADUser -Identity $username -Properties MemberOf).MemberOf
if (!($groups -match $adgroup)) {
# User is not a member of the AD group, so add to group
Add-ADGroupMember -Identity "$adgroup" -Members $username
}
}
}
Each AAD group links to a single AD group, but one AD group might be linked to multiple AAD groups.
That part is fine, I'm successfully adding users to AD groups if they're in an associated AAD group. The confusion for me comes in when I want to do the reverse afterwards. That is, for each user that is part of AD 1, if they're not in any of the AAD groups associated with that group then remove them from AD 1.
The way I've thought of doing this would be to create another hashtable where the key is the AD group, then the value is an array of AAD groups associated with that group, and iterate through each key to check if they're part of any of the value groups. How could I go about creating that hashtable automatically based on the data in the original hashtable, and how could I then iterate through multiple values for a single key?
There may be a better data structure or method for this that I'm unaware of which would make the whole thing easier, but my overall knowledge is pretty limited. Any advice would be appreciated, thanks.
You can flip your $mappings
table aroun with Group-Object
like this:
$mappings = @{
"1 - AAD Group" = "AD 1"
"1 - Another Group" = "AD 1"
"2 - Hello" = "AD 2"
"3 - Hi" = "AD 3"
"3 - Another" = "AD 3"
"3 - Again" = "AD 3"
}
$reverseMappings = $mappings.GetEnumerator() |Group -Property Value -AsHashTable
foreach($reverseMapping in $reverseMappings.GetEnumerator()){
$ADGroup = $reverseMapping.Key
foreach($AADGroup in $reverseMapping.Value.Name){
# Add AAD members here
}
}