Skip to content

Instantly share code, notes, and snippets.

@RobinBeismann
Created October 9, 2020 14:28
Show Gist options
  • Save RobinBeismann/af733d9850119b6d2070f6288578c377 to your computer and use it in GitHub Desktop.
Save RobinBeismann/af733d9850119b6d2070f6288578c377 to your computer and use it in GitHub Desktop.
Set-DelegateList.ps1
#Load Modules
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn;
Import-Module ActiveDirectory
try{
Write-Host("Retrieving AD Users")
$ADUsers = Get-ADUser -Filter * -Properties objectSID, msExchMasterAccountSid, sidHistory, msExchDelegateListLink -ErrorAction Stop
Write-Host("Retrieving Mailbox Permissions")
$MailboxPerm = Get-MailboxPermission -ResultSize Unlimited -Identity * -ErrorAction Stop
Write-Host("Retrieving Mailboxes")
$Mailboxes = Get-Mailbox -ResultSize Unlimited -ErrorAction Stop
Write-Host("Starting to process")
$Mailboxes | Foreach {
#Retrieve the mailbox from Exchange
$mailbox = $_
#Build a list of SIDs which have fullaccess on this mailbox
$sids = $MailboxPerm | Where-Object { $_.Identity.DistinguishedName -eq $mailbox.DistinguishedName } | Where-Object { $_.AccessRights -eq "FullAccess" } | Select-Object -ExpandProperty User | Select-Object -ExpandProperty SecurityIdentifier | Select-Object -ExpandProperty Value
#Get ADObject for the Mailbox
$mailboxDN = $mailbox.DistinguishedName
$adObject = $ADUsers | Where-Object { $_.distinguishedName -eq $mailboxDN }
#Get all DNs for the SIDs
$DNs = $ADUsers | Where-Object {
$sids.Contains($_.objectSID) -or
(
($_.msExchMasterAccountSid -ne "S-1-5-10") -and
($sids.Contains($_.msExchMasterAccountSid))
) -or
$sids.Contains($_.sidHistory)
} | Select-Object -ExpandProperty distinguishedName
#Check if there are unwanted Automap Links
$adObject.msExchDelegateListLink | % {
if(!($DNs.Contains($_)) -and !($_.Contains("OU=Admins,"))){
Write-Host("$($mailbox.Name): Removing $_ from Automapping list")
#$adObject | Set-ADUser -Remove @{ msExchDelegateListLink = "$_" }
}
}
#Check if there are automap links missing
$DNs | % {
if(
!($adObject.msExchDelegateListLink.Contains($_)) -and
!($_.Contains("OU=Admins,")) -and
!($_ -eq "CN=Administrator,CN=Users,DC=cotn,DC=group") -and
($mailbox.DistinguishedName -ne $_)
){
Write-Host("$($mailbox.Name): Adding $_ to Automapping list")
$adObject | Set-ADUser -Add @{ msExchDelegateListLink = "$_" }
}
}
}
}catch{
Write-Error("Error: $_")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment