Delete mailbox for non existant AD user

This section contains scripts that hMailServer has contributed with. hMailServer 5 is needed to use these.
Post Reply
tdemeyer
New user
New user
Posts: 17
Joined: 2017-07-05 12:00

Delete mailbox for non existant AD user

Post by tdemeyer » 2018-03-05 13:37

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

User avatar
jimimaseye
Moderator
Moderator
Posts: 8073
Joined: 2011-09-08 17:48

Re: Delete mailbox for non existant AD user

Post by jimimaseye » 2018-03-05 14:47

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.
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 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

tdemeyer
New user
New user
Posts: 17
Joined: 2017-07-05 12:00

Re: Delete mailbox for non existant AD user

Post by tdemeyer » 2018-03-05 17:33

After a few hours of trial and error, I found a working solution.

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..

User avatar
jimimaseye
Moderator
Moderator
Posts: 8073
Joined: 2011-09-08 17:48

Re: Delete mailbox for non existant AD user

Post by jimimaseye » 2018-03-05 19:26

That looks like exactly as I was thinking. Well done, thanks for sharing.
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 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

Post Reply