Set “Profile Sync” account permissions for SharePoint On-Premises in Active Directory via PowerShell

Here is a PowerShell script to add “Profile Sync” account in Active Directory to “Default Domain Context” and “Configuration Context”…

The outcome is the same as you would add it with ADSIEdit.

Don’t forget: Change the content of variable “$TargetAccount”

Be careful before executing the script. I’m not responsible for any damages in your system. For me it worked, but it’s up to you to test it properly!

# Just the sAMAccountName. No domain prefix!
$TargetAccount = "spprofsync"

Import-Module ActiveDirectory

# Perm 'Replicate Directory Changes ALL'
$ReplicationGuid = [Guid]"1131f6aa-9c07-11d1-f79f-00c04fc2dcd2"

try {
    $Principal = Get-ADUser -Identity $TargetAccount -ErrorAction SilentlyContinue

    if (-not $Principal) {
        $Principal = Get-ADGroup -Identity $TargetAccount -ErrorAction SilentlyContinue
    }
    
    if (-not $Principal) {
        Write-Error "User or Group '$TargetAccount' not found."
        return
    }

    Write-Host "Target Principal: $($Principal.Name) ($($Principal.SID))" -ForegroundColor Cyan

    $RootDSE = Get-ADRootDSE
    $Contexts = @(
        $RootDSE.defaultNamingContext,       # Domain Context
        $RootDSE.configurationNamingContext  # Configuration Context
    )

    $ADRight = [System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight
    $Type    = [System.Security.AccessControl.AccessControlType]::Allow
    $Rule    = New-Object System.DirectoryServices.ActiveDirectoryAccessRule(
        $Principal.SID, 
        $ADRight, 
        $Type, 
        $ReplicationGuid
    )

    foreach ($ContextDN in $Contexts) {
        Write-Host "Processing Context: $ContextDN" -NoNewline
        
        try {
            $Path = "AD:\$ContextDN"
            $Acl = Get-Acl -Path $Path
            
            $Acl.AddAccessRule($Rule)
            
            Set-Acl -Path $Path -AclObject $Acl
            Write-Host " [SUCCESS]" -ForegroundColor Green
        }
        catch {
            Write-Host " [FAILED]" -ForegroundColor Red
            Write-Error $_
        }
    }

} catch {
    Write-Error "An unexpected error occurred: $_"
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.