I have modified the script to grant user1 and user2 access to the groups listed in the attached text file. Could someone please review and validate the script?
# Define the users that will be granted permission
$owners = "user1", "user2"
# Loop through each group in the list
foreach ($group in Get-Content C:\Temp\grouplist.txt) {
if ($group.Trim() -eq "") {
continue # Skip blank lines
}
Write-Host "Processing group: $group"
try {
# Get the group object from AD
$groupObject = Get-ADGroup -Identity $group -ErrorAction Stop
} catch {
Write-Host "Could not retrieve group object for '$group'. Skipping..."
continue
}
try {
# Bind to the group via ADSI
$ldapString = "LDAP://" + $groupObject.DistinguishedName
$ldapGroup = [ADSI]$ldapString
$secOptions = $ldapGroup.get_Options()
$secOptions.SecurityMasks = [System.DirectoryServices.SecurityMasks]'Dacl'
# Loop through each owner and apply ACL
foreach ($owner in $owners) {
try {
$ownerObject = Get-ADUser -Identity $owner -ErrorAction Stop
} catch {
Write-Host "Could not retrieve user object for '$owner'. Skipping..."
continue
}
$sid = New-Object System.Security.Principal.SecurityIdentifier($ownerObject.SID.Value)
$adRights = [System.DirectoryServices.ActiveDirectoryRights]::WriteProperty
$accessType = [System.Security.AccessControl.AccessControlType]::Allow
$writeMembersGuid = [Guid]"bf9679c0-0de6-11d0-a285-00aa003049e2"
$adRule = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($sid, $adRights, $accessType, $writeMembersGuid)
$acl = $ldapGroup.ObjectSecurity
$acl.AddAccessRule($adRule)
$ldapGroup.ObjectSecurity = $acl
Write-Host "Granted '$owner' WriteMembers rights on group '$group'"
}
# Commit all changes
$ldapGroup.CommitChanges()
} catch {
Write-Host "Failed to apply ACLs on group '$group'. Error: $_"
continue
}
}