Assigning Unix Attributes to Active Directory Objects

I run Active Directory to manage my users and groups. Most of my servers run Linux, and I also run a Synology DiskStation that serves files via NFS and CIFS. To keep file permissions and ownership consistent, I assign static UID and GID values to my Active Directory users and groups. Rather than manually assigning UID and GID values, I created a PowerShell script to do it for me.

$objectBase = "ou=Digital Lotus,dc=corp,dc=digitallotus,dc=com"
$idRangeBase = 100000
$primaryGid = 101110
$loginShell = "/bin/bash"
$homeDirectoryBase = "/users"

Get-ADObject `
        -LDAPFilter "(&(|(objectClass=user)(objectClass=group))(!objectClass=computer))" `
        -SearchBase "$objectBase" `
        -Properties objectClass,objectSid,uidNumber,gidNumber,sAMAccountName,loginShell,unixHomeDirectory,primaryGroupID | ForEach {
        
    $sAMAccountName = $_.sAMAccountName
    $objectRid = ($_.objectSid -split "-")[-1]
    $idNumber = $idRangeBase + $objectRid

    if ( $_.objectClass -eq "user" ) {
        if ( -not $_.uidNumber ) {
            Write-Host "Adding uidNumber $idNumber to $sAMAccountName"
            $_ | Set-ADObject -Add @{uidNumber=$idNumber}
        }
        if ( -not $_.gidNumber ) {
            Write-Host "Adding gidNumber $gidNumber to $sAMAccountName"
            $_ | Set-ADObject -Add @{gidNumber=$primaryGid }
        }
        if ( -not $_.loginShell ) {
            Write-Host "Adding loginShell $loginShell to $sAMAccountName"
            $_ | Set-ADObject -Add @{loginShell=$loginShell}
        }
        if ( -not $_.unixHomeDirectory ) {
            $homeDirectory = "$homeDirectoryBase/$sAMAccountName"
            Write-Host "Adding unixHomeDirectory $homeDirectory to $sAMAccountName"
            $_ | Set-ADObject -Add @{unixHomeDirectory=$homeDirectory}
        }
    }

    if ( $_.objectClass -eq "group" -and -not $_.gidNumber ) {
        Write-Host "Adding gidNumber $idNumber to $sAMAccountName"
        $_ | Set-ADObject -Add @{gidNumber=$idNumber}
    }

}

The objectBase variable is the base of the search for users and groups, and idRangeBase is the starting value for the IDs. The Active Directory object's relative ID is added to idRangeBase to create the actual UID or GID number.

#activedirectory #powershell