Automating Home Directory Settings for Active Directory Users with PowerShell

· 1 min read
Automating Home Directory Settings for Active Directory Users with PowerShell
Photo by Maik Jonietz / Unsplash

Here is a script that simplifies the process of setting home directories for users in Active Directory.

The Script:

# Define the log file path
$logFilePath = "C:\PathToLogFile\AD_HomeDirectory_Setting.log"

# Start transcript to log the script's output
Start-Transcript -Path $logFilePath

# Define the target OU and home directory path
$targetOU = "OU=UsersWorldcom,DC=worldcom,DC=local"  # Replace with your specific OU path
$homeDirectory = "\\server\share\%username%"    # Replace with the desired home directory path

# Get a list of user objects in the target OU
$users = Get-ADUser -Filter * -SearchBase $targetOU

# Loop through each user and set the home directory value
foreach ($user in $users) {
    # Construct the path for the home directory
    $homeDirectoryPath = $homeDirectory -replace "%username%", $user.SamAccountName

    # Set the home directory for the user
    Set-ADUser -Identity $user -HomeDirectory $homeDirectoryPath -HomeDrive "P"  # You can change the HomeDrive letter as needed

    # Log the action for each user
    Write-Output "Home directory for $($user.SamAccountName) set to $homeDirectoryPath"
}

# Stop the transcript to finish logging
Stop-Transcript

Here's a breakdown of the script:

  1. Log File Definition:The script begins by defining a log file path and starting a transcript to log the script's output. This is crucial for keeping a record of the actions performed.
  2. Target OU and Home Directory Path:The script specifies the target Organizational Unit (OU) and the desired home directory path. You should customize these values to match your specific Active Directory structure and file server paths.
  3. Getting User Objects:It retrieves a list of user objects in the specified OU using the Get-ADUser cmdlet.
  4. Loop Through Users:The script loops through each user in the specified OU, constructs the path for their home directory by replacing "%username%" with their SamAccountName, and then sets the home directory and drive letter (in this case, "P") for each user. It logs the action for each user in the transcript.
  5. Stop Transcript:The script ends by stopping the transcript, ensuring that all actions are recorded in the log file.