We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.

Script repository

Enable/Disable ActiveSync Exchange feature based on group membership

February 18, 2021 Views: 4448

The script enables the ActiveSync feature for Exchange mailboxes who are members of a specific group, and disables the feature for those members who are not part of the group. Also, the script creates CSV reports containing all users who have the feature enabled before and after processing user accounts.

To update the ActiveSync feature on a regular basis to keep in sync with changes in the group membership, you need to create a scheduled task configured for the Domain-DNS object type. To add the script to your task, use the Run a program or PowerShell script action.

Parameters:

  • $groupDN - Specifies the Distinguished Name (DN) of the groups whose members have the ActiveSync feature enabled.
  • $reportPathBeforeUpdate - Specifies a path for the CSV report containing users who had the feature enabled before running the script.
  • $reportPathAfterUpdate - Specifies a path for the CSV report containing users who have the feature enabled after the script run.

Edit Remove
PowerShell
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MM-dd-yyyy_hh-mm-ss')

$groupDN = "CN=ACTIVE_SYNC_ALLOWED,OU=Exchange Objects,DC=example,DC=com" # TODO: modify me
$reportPathBeforeUpdate = "\\SERVER\Share\Reports\BeforeRunActiveSyncEnabled_$CurrentDate.csv" # TODO: modify me
$reportPathAfterUpdate = "\\SERVER\Share\Reports\AfterRunActiveSyncEnabled_$CurrentDate.csv" # TODO: modify me

# Script block to be executed in an external instance of PowerShell
$scriptBlock = {
    Import-Module Adaxes

    function UpdateActiveSync ($userInfos)
    {
        # Update ActiveSync for user
        foreach ($userGuid in $userInfos.Keys)
        {
            $userPath = 'Adaxes://<GUID=' + $userGuid + '>;'
            $user = $admService.OpenObject($userPath, $NULL, $NULL, 0)

            # Check whether the user has an Exchange mailbox
            if ($user.RecipientType -ine 'ADM_EXCHANGERECIPIENTTYPE_MAILBOXENABLED')
            {
                continue
            }

            try
            {
                # Get Exchange properties
                $mailboxParams = $user.GetMailParameters()
            }
            catch
            {
                continue
            }

            # Get ActiveSync settings
            $activeSync = $mailboxParams.MailboxFeatures.GetItemByType(
                'ADM_EXCHANGE_MAILBOXFEATURETYPE_ACTIVESYNC')

            # Enable/disable ActiveSync
            $activeSync.Enabled = $userInfos[$userGuid]

            try
            {
                $user.SetMailParameters($mailboxParams, 'ADM_SET_EXCHANGE_PARAMS_FLAGS_NONE')
            }
            catch
            {
                continue
            }
        }
    }

    # Build LDAP filter to search for users with ActiveSync Enabled
    $activeSyncEnabledFilter = New-Object "System.Text.StringBuilder"
    $activeSyncEnabledFilter.Append('(&(sAMAccountType=805306368)(mailNickname=*)(!(cn=SystemMailbox{*))(msExchHomeServerName=*)(msExchVersion=*)') | Out-Null

    [int]$airSyncDisabled = 4
    $activeSyncDisabledPart = [Softerra.Adaxes.Ldap.FilterBuilder]::CreateBitAndMatch('msExchOmaAdminWirelessEnable', $airSyncDisabled)
    $activeSyncEnabledFilter.Append([Softerra.Adaxes.Ldap.FilterBuilder]::CreateNegation($activeSyncDisabledPart)) | Out-Null

    $activeSyncEnabledFilter.Append(')') | Out-Null
    $activeSyncEnabledFilter = $activeSyncEnabledFilter.ToString()

    # Search all users with ActiveSync enabled
    $users = Get-AdmUser -LdapFilter $activeSyncEnabledFilter `
        -SearchBase '%distinguishedName%' -SearchScope SubTree `
        -Server $domainName -AdaxesService localhost `
        -Properties DisplayName, SamAccountName, mail

    $userActiveSyncEnabled = New-Object "System.Collections.Generic.HashSet[System.Guid]"
    foreach ($userID in $users)
    {
        $userActiveSyncEnabled.Add($userID.ObjectGUID) | Out-Null
    }

    # Backup status before script run
    $users | Select-Object DisplayName, SamAccountName, mail | Sort-Object DisplayName `
        | Export-Csv -Path $reportPathBeforeUpdate -NoTypeInformation

    # Bind to the group
    $admNS = New-Object "Softerra.Adaxes.Adsi.AdmNamespace"
    $admService = $admNS.GetServiceDirectly('localhost')

    $groupPath = 'Adaxes://' + $groupDN
    $group = $admService.OpenObject($groupPath, $NULL, $NULL, 0)

    # Build filter to search for members of the group
    $groupMemberFilter = New-Object "System.Text.StringBuilder"
    $groupMemberFilter.Append('(&(sAMAccountType=805306368)(|') | Out-Null
    foreach ($memberGuidInByte in $group.GetEx('adm-MembersGuid'))
    {
        $memberGuid = New-Object "System.Guid" (,$memberGuidInByte)
        $groupMemberFilter.Append([Softerra.Adaxes.Ldap.FilterBuilder]::Create('objectGUID', $memberGuid)) | Out-Null
    }

    # Finish building filter
    $groupMemberFilter.Append('))') | Out-Null
    $groupMemberFilter = $groupMemberFilter.ToString()

    # Search all users who are members of the group
    $memberGuids = Get-AdmUser -LdapFilter $groupMemberFilter `
        -SearchBase '%distinguishedName%' -SearchScope SubTree `
        -Server $domainName -AdaxesService localhost


    # Get users who need to be enabled for ActiveSync
    $userInfos = @{}
    foreach ($memberID in $memberGuids)
    {
        if ($userActiveSyncEnabled.Contains($memberID.ObjectGUID))
        {
            $userActiveSyncEnabled.Remove($memberID.ObjectGUID) | Out-Null
            continue
        }

        # Enable ActiveSync
        $userInfos.Add($memberID.ObjectGUID, $True) | Out-Null
    }

    # Get users who need to be disabled for ActiveSync
    foreach ($userGuid in $userActiveSyncEnabled)
    {
        $userInfos.Add($userGuid, $False) | Out-Null
    }

    # Enable/Disable ActiveSync
    UpdateActiveSync $userInfos

    # Search for users with ActiveSync enabled again
    Get-AdmUser -LdapFilter $activeSyncEnabledFilter -Server $domainName -AdaxesService localhost `
        -SearchBase '%distinguishedName%' -SearchScope SubTree `
        -Properties DisplayName, SamAccountName, mail | Select-Object DisplayName, SamAccountName, mail `
        | Sort-Object DisplayName | Export-Csv $reportPathAfterUpdate -NoTypeInformation

}
# Script block end

# Start Windows PowerShell as a separate process and run the script block in that process
$domainName = $Context.GetObjectDomain("%distinguishedName%")
$powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
Start-Process $powershellPath -NoNewWindow `
    -ArgumentList ("-ExecutionPolicy Bypass -noninteractive -noprofile `$domainName = '$domainName'; `$reportPathBeforeUpdate = '$reportPathBeforeUpdate'; `$reportPathAfterUpdate = '$reportPathAfterUpdate'; `$groupDN = '$groupDN';" + $scriptBlock )

Comments 2
avatar
Sandra Mitchell Sep 29, 2020
I'm unable to get this to work. I suspect it may have something to do with the Activity Scope, but I'm not sure. Can someone reach out so that I can provide specifics.

Thanks...
avatar
Support Sep 30, 2020
Hello Sandra,

What exactly is not working? Do you face any error messages? If so, please, provide us with screenshots.

Could you, please, post here or send us (support[at]adaxes.com) the script you are using in TXT format including all your modifications?

Also, provide us with a screenshot of the Custom Command, Business Rule or Scheduled Task that executes the script. If it is a Business Rule or Scheduled Task, please, include the Activity Scope section into the screenshot.
avatar
Sandra Mitchell Oct 27, 2020
I'll respond via email...
Leave a comment
Loading...

Got questions?

Support Questions & Answers