Powershell script to create user home directory and DFS namespace target
Creating a new users home directory and corresponding DFS namespace target. The script can also force all domain controllers to fully sync up in case you have multiple sites. Sync is enabled by default, however it can be disabled. This powershell script does require WinRM to be enabled for sync to work. You need to have setup the DFS namespace root path already.
CreateHome -user $target -server $server -dfsNamespacePath "\\example.com\UserFolders" -sync $true
Function CreateHome {
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True,Position=0)]
[string]$user,
[Parameter(Mandatory=$True,Position=1)]
[string]$server,
[Parameter(Mandatory=$True,Position=2)]
[string]$dfsNamespacePath,
[Parameter(Mandatory=$False,Position=3)]
[bool]$sync = $true
)
if ($sync)
{
write-host "Syncing Changes..."
$dcs = Get-ADComputer -Filter * -Properties * | Where-Object { $_.CanonicalName.contains('/Domain Controllers/', "CurrentCultureIgnoreCase") }
$dcs | ForEach-Object {
Write-Host "Syncing $($_.Name)"
$res = Invoke-Command -ComputerName $_.Name -ScriptBlock { repadmin /syncall /AdeP }
write-host "Syncing Complete..."
}
}
trap {continue} New-Item -Path "$server\$user" -type Directory -ErrorAction SilentlyContinue
$Path = "$server\$user"
$acl = (Get-Item $Path).GetAccessControl('Access')
$allInherit = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit", "ObjectInherit"
$allPropagation = [System.Security.AccessControl.PropagationFlags]"None"
$permissions = "FullControl"
$Username = "$user"
$AR = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, $permissions, $allInherit, $allPropagation, "Allow")
if ($acl.Access | Where { $_.IdentityReference -eq $Username})
{
$accessModification = New-Object System.Security.AccessControl.AccessControlModification
$accessModification.value__ = 2
$modification = $false
$acl.ModifyAccessRule($accessModification, $AR, [ref]$modification) | Out-Null
}
else
{
$acl.AddAccessRule($AR)
}
Set-Acl -path $Path -AclObject $Acl
$result = dfsutil link add "$dfsNamespacePath\$user" "$server\$user"
}