-
Notifications
You must be signed in to change notification settings - Fork 1
/
Flatten AD Groups to Azure Group.ps1
77 lines (68 loc) · 2.73 KB
/
Flatten AD Groups to Azure Group.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
###########
### Synchronize the contents of multiple AD groups to a single Azure AD group. Flatten any nested AD groups.
############
Import-Module ActiveDirectory
######## Environment variables
$SecurityGroups = "MyGroup1", "MyGroup2" # Array of AD group names
$AzGroup = "<guid>" # ObjectId of Azure group
######## Establish connection to Azure
# There are better ways to do this, such as passing in credentials from Azure secure storage at runtime
$password = "a secure password" | ConvertTo-SecureString -asPlainText -Force
$azdcred = New-Object PSCredential "account@domain.edu", $password
Connect-AzureAD -Credential $azdcred
######## Get contents of AD and Azure groups
try {
foreach ($SG in $SecurityGroups) {
$Group = Get-ADGroup $SecurityGroup
$ADUsers += Get-ADGroupMember -Identity $Group -Recursive | Get-ADUser #| Get-AzureADUser -ObjectId {$_.UserPrincipalName} | Select-Object -Property UserPrincipalName, ObjectId
}
Write-Output ""
Write-Output "AD Users"
Write-Output "--------"
Write-Output $ADUsers.Length
Write-Output ""
# $ADUsers | Where-Object {$_.UserPrincipalName -eq 'wbest@mcny.edu'} # Debug
$AzureUsers = Get-AzureADGroupMember -ObjectId $AzGroup -All $true | Select-Object -Property UserPrincipalName, ObjectId
Write-Output "Azure AD Users"
Write-Output "---------"
Write-Output $AzureUsers.Length
Write-Output ""
}
catch {
throw $_
}
######## Compare contents as arrays and make necessary adjustments
if (($null -ne $ADUsers) -and ($null -ne $AzureUsers)) {
$comparedefault = Compare-Object -ReferenceObject $ADUsers -DifferenceObject $AzureUsers
Write-Output "Group Comparison Results"
Write-Output "---------"
Write-Output $comparedefault
Write-Output ""
if ($comparedefault.SideIndicator -eq "<=") {
foreach ($User in $comparedefault.InputObject) {
Add-AzureADGroupMember -ObjectId $AzGroup -RefObjectId $User.ObjectId
Write-Output "$User added to Azure group."
}
}
elseif ($comparedefault.SideIndicator -eq "=>") {
foreach ($User in $comparedefault.InputObject) {
Remove-AzureADGroupMember -ObjectId $AzGroup -MemberId $User.ObjectId
Write-Output "$User removed from Azure group."
}
}
else {
Write-Output "No changes to make."
}
}
elseif ($null -eq $AzureUsers) {
foreach ($User in $ADUsers) {
Add-AzureADGroupMember -ObjectId $AzGroup -RefObjectId $User.ObjectId
Write-Output "$User added to Azure group."
}
}
elseif ($null -eq $ADUsers) {
foreach ($User in $AzureUsers) {
Remove-AzureADGroupMember -ObjectId $AzGroup -MemberId $User.ObjectId
Write-Output "$User removed from Azure group."
}
}