Private Folders mounted by ADUC HomeDirectory attribute
While most organizations are moving files to cloud-based solutions, I'm working for a client who wants to keep everything in-house. In this environment, some users had a private folder under a previous drive letter mapping, others didn't have anything at all.
I created this quick and dirty Powershell script to automate the cleanup process for existing users.
This script gets all users from AD, sets their HomeDirectory attribute in AD to a fileshare and mounts it on the U: drive, and creates private folders with the correct ACL permissions.
# Assign-PrivateDrive
# Tim D'Annecy 2021-07-09
# Creates shared drive folder with correct permissions and sets AD property.
function Assign-PrivateDrive {
param()
Import-Module ActiveDirectory
$driveLetter = 'U:'
$PrimaryDC = 'sample.dc'
$activeOUDN = 'OU=Users,DC=sample,DC=local'
$users = Get-ADUser -Filter { Enabled -eq $true } -SearchBase $activeOUDN -Properties *
foreach ($user in $users) {
$UserSAM = $user.SamAccountName
$fullPath = "\\samplefs\share\Private\{0}" -f $UserSAM
Set-ADUser -Server $PrimaryDC -Identity $UserSAM -HomeDrive $driveLetter -HomeDirectory $fullPath
if (!(Test-Path -Path $fullPath )) {
Write-Host "Creating directory at $fullPath"
New-Item -path $fullPath -ItemType Directory
$acl = Get-Acl $fullPath
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ("sample\$UserSAM", $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl.AddAccessRule($AccessRule)
Write-Host 'Setting permissions on folder.'
Set-Acl -Path $fullPath -AclObject $acl
}
else {
Write-Host "Skipping $($user.Name) . Directory found at $fullPath"
}
}
}
Assign-PrivateDrive