I can create user accounts with a CSV ok in Powershell.
I can also create an account from a template account in Powershell, and the info like address & group memberships comes across ok.
However, when trying to combine both operations inside of a foreach loop, the additional info from the template account will not populate into the new accounts created from the CSV.
I tried using variables to capture the Template User properties, to include using a variable to capture only the group info from the template account.
I also tried using specific names for the accounts instead of variables. However, the data from the template account does not go over to the accounts created from CSV in the foreach loop.
You can see in the below images, that the data never populates in the newly created users. (I don’t know why the images aren’t showing, it showed me a thumbnail & gave me option to "Add Image")
You can see in the following code the things that I have tried:
#------------------------- Create users with CSV & Template -------------------------------
# Goal = to get all settings from template account to include city, address, & groups
# into each account that is being created from the CSV.
# The accounts create, but the other data (address & groups) do not populate.
# Import the CSV file
$users = Import-Csv -Path "C:\Users\Administrator\Desktop\Posh_Server2022\AD\Users.csv"
# Get the template user
$templateUser = Get-ADUser -Identity "Template User"
# Loop through each user in the CSV file
foreach ($user_ in $users) {
# Create the new user based on the template
New-ADUser -Name $user_.Name `
-GivenName $user_.GivenName `
-Surname $user_.Surname `
-SamAccountName $user_.UserName `
-AccountPassword $user_.Password `
-Instance $templateUser
# Get the groups that the template user is a member of
#$groups = Get-ADPrincipalGroupMembership -Identity $templateUser
############## THIS IS WHERE PROBLEMS START ##############
#$tmpltUsr = Get-ADUser 'Template User' -Properties MemberOf
#$tmpltUsr = Get-ADUser 'Template User' # THIS GIVES NO ERRORS BUT DOESN'T WORK
#$tmpltUsr = Get-ADPrincipalGroupMembership -Identity "Template User"
#ForEach($group in 'Template User'.MemberOf){
# ForEach($group in $groups){
ForEach($group in $templateUser.MemberOf){ # THIS GIVES NO ERRORS BUT DOESN'T WORK
# ForEach($group in $templateUser){
Add-ADGroupMember $group -Members $user_ #THIS GAVE NO ERRORS
#Add-ADGroupMember -Identity $group.Name -Members $user_
}
}
###################################################
CSV:
Name,GivenName,Surname,UserName,AccountPassword
Test User1,Test,User1,tuser1,Password
Test User2,Test,User2,tuser2,Password
You need to sign in to view this answers
Leave feedback about this