Making home folders for every user
This script does the following:
- reads out you're CSV file and makes a shared folder for every user.
- sets the right permissions so not everyone can access it, but the user itself can.
what do you need to make this script work?
- Have a CSV file with all you're users set up in "C:\Temp\users.csv"
- have you're CSV file set up as "Voornaam,Achternaam,Gebruikersnaam,Afdeling"
- having set up an additional disk with disk letter 'E'
- have a map named 'profiles' set up on you're additional disk (E:\Profiles)
The script:
Import-Module ActiveDirectory
# Path where profiles will be stored
$BasePath = "E:\Profiles"
# CSV with usernames (adjust column name if different!)
$CsvPath = "C:\Temp\users.csv"
# Local administrators group (change if your domain has a different admin group)
$AdminGroup = "BUILTIN\Administrators"
# Import CSV
$Users = Import-Csv -Path $CsvPath
foreach ($User in $Users) {
# Adjust this line to match your CSV header
$Sam = $User.Gebruikersnaam
if ([string]::IsNullOrWhiteSpace($Sam)) {
Write-Warning "Skipping row because username is empty"
continue
}
$UserFolder = Join-Path $BasePath $Sam
# Create the folder if it doesn’t exist
if (!(Test-Path $UserFolder)) {
New-Item -Path $UserFolder -ItemType Directory | Out-Null
Write-Host "Created folder $UserFolder"
}
# Reset NTFS permissions
$Acl = Get-Acl $UserFolder
$Acl.SetAccessRuleProtection($true, $false) # disable inheritance
# Remove all existing permissions
$Acl.Access | ForEach-Object { $Acl.RemoveAccessRule($_) }
# Add user full control
$AccessRuleUser = New-Object System.Security.AccessControl.FileSystemAccessRule("$Sam", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.AddAccessRule($AccessRuleUser)
# Add Administrators full control
$AccessRuleAdmin = New-Object System.Security.AccessControl.FileSystemAccessRule($AdminGroup, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.AddAccessRule($AccessRuleAdmin)
# Apply ACL
Set-Acl -Path $UserFolder -AclObject $Acl
Write-Host "Set NTFS permissions for $Sam"
# Share the folder (hidden share with $)
$ShareName = $Sam + "$"
if (-not (Get-SmbShare -Name $ShareName -ErrorAction SilentlyContinue)) {
New-SmbShare -Name $ShareName -Path $UserFolder -FullAccess $Sam,$AdminGroup
Write-Host "Created share $ShareName for $Sam"
}
# Set as home folder in AD (H:)
$HomePath = "\\$env:COMPUTERNAME\$ShareName"
Set-ADUser $Sam -HomeDirectory $HomePath -HomeDrive "H:"
Write-Host "Linked $Sam home folder to $HomePath"
}