function New-HomeFolder {
param([string]$Username)
$path = "D:\Homes\$Username"

if (Test-Path $path) {
    Write-Host "$path already exists - verifying subfolders"
} else {
    New-Item -ItemType Directory -Path $path -Force | Out-Null
    $acl = New-Object System.Security.AccessControl.DirectorySecurity
    $acl.SetAccessRuleProtection($true, $false)
    $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("CASCADES\$Username","FullControl","ContainerInherit,ObjectInherit","None","Allow")))
    $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM","FullControl","ContainerInherit,ObjectInherit","None","Allow")))
    $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl","ContainerInherit,ObjectInherit","None","Allow")))
    Set-Acl $path $acl
    Write-Host "$path created with clean ACL"
}

# Pre-create all redirect subfolders so fdeploy never fails on first logon.
# fdeploy caches failures and won't retry if subfolders don't exist at first logon.
foreach ($folder in @("Desktop","Documents","Downloads","Music","Pictures")) {
    $sub = "$path\$folder"
    if (Test-Path $sub) {
        Write-Host "  $sub already exists"
    } else {
        New-Item -ItemType Directory -Path $sub -Force | Out-Null
        $acl = New-Object System.Security.AccessControl.DirectorySecurity
        $acl.SetAccessRuleProtection($true, $false)
        $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("CASCADES\$Username","FullControl","ContainerInherit,ObjectInherit","None","Allow")))
        $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM","FullControl","ContainerInherit,ObjectInherit","None","Allow")))
        $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl","ContainerInherit,ObjectInherit","None","Allow")))
        Set-Acl $sub $acl
        Write-Host "  Created: $sub"
    }
}
}

# Usage: dot-source this file on CS-SERVER, then call:
#   New-HomeFolder -Username "lauren.hasselman"
#
# IMPORTANT: Run this BEFORE adding the user to SG-FolderRedirect and BEFORE
# their first domain logon. fdeploy caches failures — if it runs before
# subfolders exist it will say "no changes detected" on all future logons and
# never retry.
#
# If a user already logged in and redirection failed, use
# fix-shell-redirect.ps1 on the client machine instead.
