Hi script guru's out there...
I've been using a PS script to automatically create mailboxes for members of a given AD group (see another post of me). This works fine, but
I'm in need of a utility that does just the opposite: run through all mailboxes and if the corresponding user is no longer found to be member of the AD group, then delete the mailbox.
Any suggestion is welcome...
Tim
Delete mailbox for non existant AD user
- jimimaseye
- Moderator
- Posts: 8917
- Joined: 2011-09-08 17:48
Re: Delete mailbox for non existant AD user
Should be easy enough for you. The documentation https://www.hmailserver.com/documentati ... e=overview and examples https://www.hmailserver.com/documentati ... m_examples will show you how to cycle through the domain accounts and obtain the email address from each account. The pass that variable in to your script that then looks it up in AD.
5.7 on test.
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829
Re: Delete mailbox for non existant AD user
After a few hours of trial and error, I found a working solution.
If anyone is interested...
Maybe there's room for some cleaning up or tweaking, but at least this works..
If anyone is interested...
Code: Select all
Import-Module ActiveDirectory
$group = "ADGroupname"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
$hm = New-Object -ComObject hMailServer.Application
$hm.Authenticate("admin", "adminpassword") | out-null
$hmdom = $hm.Domains.ItemByName("staff.acme.com")
$hmdomaccts = $hmdom.Accounts.Count()
for ($i=$hmdomaccts-1;$i -ge 0;$i=$i-1) {
$hmdomacct = $hmdom.Accounts.Item($i)
$user = $hmdomacct.ADUsername
If ( -not ($members -contains $user)) {
$mailaddr = $hmdomacct.Address
$acctID = $hmdom.Accounts.ItemByAddress($mailaddr)
$hmdom.Accounts.DeleteByDBID($acctID.ID)
}
}
Maybe there's room for some cleaning up or tweaking, but at least this works..
- jimimaseye
- Moderator
- Posts: 8917
- Joined: 2011-09-08 17:48
Re: Delete mailbox for non existant AD user
That looks like exactly as I was thinking. Well done, thanks for sharing.
5.7 on test.
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829