Recently I needed to create lots of users and homedirectories. This gave a me an challenge. How can I grant rights on a homefolder in seconds after creating an user.
If you create a user and then a folder, then set the rights. Go to the properties>securities tab, if you search for the user it takes a while before the domain controller has information about the new user.
So how do you create thousands of users without setting long delays to allow for Active Directory replication? You turn to SIDs. The SID is the Security Identifier of the account, its the SID that is saved in the ACL.
#Import the ActiveDirectory Module for easy access to create a new user
Import-Module ActiveDirectory
#Select which controller to work with
$DomainController = (Get-ADDomain).PDCEmulator
#Decide what user to create
$Username = 'testuser'
#Where to store the home Folder
$HomeFolder = '\servershare'+$username
#Create the user
$SIDIdentity = New-ADUser -Server:$DomainController -Name $username -HomeDrive 'D:' -HomeDirectory $homeFolder -PassThru | Select-Object -ExpandProperty SID
#Build the new HomeFolder ACE using the SID Identity
$HF_ace = New-Object System.Security.AccessControl.FileSystemAccessRule ($SIDIdentity, 'FullControl', ('ContainerInherit','ObjectInherit'), 'None','Allow')
#Create the homefolder
New-Item -Type Directory $HomeFolder | Out-Null
#Read the ACL from the new directory
$ACL = Get-ACL -Path $HomeFolder
$ACL.SetOwner((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544'))) #Administrators group, same for all localizations
#Add our ACE to the ACL
$ACL.AddAccessRule($HF_ace)
#Store the new ACL to the Home Folder.
Set-Acl -Path $HomeFolder -AclObject $ACL
If you go into the securites tab now you should see the SID unless you are already talking to the same DC that created the user.
So I got a comment from Francis Favorini that I could simplify the account creation and SID retrieval parts. So I implemented those parts too.