Automation Creation AD and add users in group

I need help, I can already create users with csv, I need to add the created users to groups that a mirror user belongs to. here’s what I’ve done so far. I couldn’t evolve

Start-Transcript -Path c:\temp\usersbra.log -Append

Import active directory module for running AD cmdlets

Import-Module ActiveDirectory

#Usuario espelho
$Userespelho = “francisco.chiquim”

#Arquivo CSV
$Users = Import-Csv -Path “C:\temp\NewUsers.csv”

foreach ($User in $Users)
$Groupsadd = Get-ADPrincipalGroupMembership $Userespelho | Select Name
Write-Output “Group Existe”
$Displayname = $User.‘Firstname’ + " " + $User.‘Lastname’
$UserFirstname = $User.‘Firstname’
$UserLastname = $User.‘Lastname’
$OU = $User.‘OU’
$SAM = $User.‘SAM’
$UPN = $User.‘Firstname’ + “.” + $User.‘Lastname’ + “@” + $User.‘Maildomain’
$Description = $User.‘Description’
$Password = $User.‘Password’
New-ADUser -Name “$Displayname” -DisplayName “$Displayname” -SamAccountName $SAM -UserPrincipalName $UPN -GivenName “$UserFirstname” -Surname “$UserLastname” -Description “$Description” -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path “$OU” -ChangePasswordAtLogon $false –PasswordNeverExpires $true -server alglab.local
Write-Host $user.SAM “Foi criado”
Add-ADGroupMember $Groupsadd $SAM

Bem-vindo to the forum. :wave:t3:

Before we proceed … please go back, edit your question once again and fix the formatting of your code.

When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in 1 <---- Click :point_up_2:t4: :wink:

(Sometimes the preformatted text button hides behind the setting gear :point_up_2:t4: :wink: )

I would strongly advise against mirroring another existing user for group membership to be given to a new employee. Over time users can accumulate membership in groups that may not be appropriate to give to a brand-new employee. This can lead to security problems or simply access to confidential data they should not.

I would encourage rather have a vetted list of groups the new employee needs and feed that into your script by means other than mirroring and existing user.

1 Like

Agree with @Matt here. Copying existing users is bad practice and risks exposing sensitive data.
If you absolutely must, you could create a (couple of) inactive template user(s) and work from, but I would rather recommend building a role based template instead.
Here’s a thread where a number of those issues are discussed: AD Account Creation
There may be something that can give you some ideas going forward.