I would like to set the home directory based on a csv file containing a list of usernames.
I imagine there is a combination of get-user, set-user, and foreach commands that give the correct updates. Here is the code I am using but I'm unable to make the logical jump to piping this output to a Set-ADUser command which sets the home directory.
function ConvertUser($user)
{
$search = New-Object DirectoryServices.DirectorySearcher([ADSI]“”)
$search.filter = “(&(objectClass=user)(displayName=$user))”
$results = $search.Findall()
foreach($result in $results){
$userEntry = $result.GetDirectoryEntry()
Write-Output($userEntry.sAMAccountName)
}
}
function ConvertUsers
{
process{
foreach($user In $_){
ConvertUser($user)
}
}
}
Get-Content ".Users.txt" | ConvertUsers
I'm sure I'm missing something simple but alas I am a Powershell newb.
Edit: I would like to have the output from ConverUsers which is the username and then pipe that to the set-aduser command. Any time I try and pipe it to set-aduser I either get syntax errors, empty pipe, or the wrong data output.
You're looking for the Set-ADUser
cmdlet. It has a -HomeDirectory
parameter, which obviously allows you to set the user's home directory, and an -Identity
parameter that specifies which user you are editing. It also has a -HomeDrive
parameter that specifies the drive letter for their home directory.
# 1. Get the user, based on their "display name"
$User = Get-ADUser -LDAPFilter '(&(displayname=Trevor Sullivan))';
# 2. Change the user's home directory and home drive
Set-ADUser -Identity $User.SamAccountName -HomeDirectory \\fileserver\users\trevor -HomeDrive U;
Given the following CSV file contents:
The following script should set the home drives:
# 1. Import the user data from CSV
$UserList = Import-Csv -Path c:\test\Users.csv;
# 2. For each user ...
foreach ($User in $UserList) {
# 2a. Get the user's AD account
$Account = Get-ADUser -LDAPFilter ('(&(displayname={0}))' -f $User.DisplayName);
# 2b. Dynamically declare their home directory path in a String
$HomeDirectory = '\\fileserver\users\{0}' -f $Account.SamAccountName;
# 2c. Set their home directory and home drive letter in Active Directory
Set-ADUser -Identity $Account.SamAccountName -HomeDirectory $HomeDirectory -HomeDrive u;
}