PowerShell: Add Users to AD and Add them in Groups - powershell

I have script which is working fine, which creates a new Active Directory user. I need to modify the script to add the user to their security group.
Here is what the contents of my CSV file look like:
Firstname,Lastname,Password,Sam,Group
Alice,Gadbois,azerty+123,a.gadbois,GG1
Quincy,Lagueux,azerty+123,q.lagueux,GG1
and here is my PowerShell script:
$objOU = [ADSI]"LDAP://OU=TestOU,DC=Domain,DC=local";
$dataSource = import-csv -Path "c:\users.csv";
foreach($dataRecord in $datasource) {
$cn = $dataRecord.FirstName + " " + $dataRecord.LastName
$sAMAccountName = $dataRecord.Sam
$givenName = $dataRecord.FirstName
$Password = $dataRecord.Password
$sn = $dataRecord.LastName
$sAMAccountName = $sAMAccountName.ToLower()
$displayName = $sn + ", " + $givenName
$userPrincipalName = $sAMAccountName + “#domain.local"
$objUser = $objOU.Create("user","CN="+$cn)
$objUser.Put("sAMAccountName",$sAMAccountName)
$objUser.Put("userPrincipalName",$userPrincipalName)
$objUser.Put("displayName",$displayName)
$objUser.Put("givenName",$givenName)
$objUser.Put("sn",$sn)
$objUser.SetInfo()
$objUser.psbase.InvokeSet(“AccountDisabled",$false)
$objUser.SetInfo()
}
I need to add a new command in the script, to add each user to his group.

Use the ActiveDirectory PowerShell module that's included with the Remote Server Administration Tools (RSAT). It has a command called Add-ADGroupMember.
http://technet.microsoft.com/en-us/library/ee617210.aspx

Here you go:
As Trevor said, you need to import the Active Directory module at the top of your script.
Import-module ActiveDirectory
And then within your foreach loop, you can add the Add-ADGroupMember Command.
foreach($dataRecord in $datasource) {
$cn = $dataRecord.FirstName + " " + $dataRecord.LastName
$sAMAccountName = $dataRecord.Sam
$givenName = $dataRecord.FirstName
$Password = $dataRecord.Password
$sn = $dataRecord.LastName
$sAMAccountName = $sAMAccountName.ToLower()
$displayName = $sn + ", " + $givenName
$userPrincipalName = $sAMAccountName + “#domain.local"
$objUser = $objOU.Create("user","CN="+$cn)
$objUser.Put("sAMAccountName",$sAMAccountName)
$objUser.Put("userPrincipalName",$userPrincipalName)
$objUser.Put("displayName",$displayName)
$objUser.Put("givenName",$givenName)
$objUser.Put("sn",$sn)
$objUser.SetInfo()
$objUser.psbase.InvokeSet(“AccountDisabled",$false)
$objUser.SetInfo()
Add-ADGroupMember -Identity $dataRecord.Group -Member $sAMAccountName
}
Troubleshooting
Verify that each user has group properly assigned:
$users = Import-Csv "Path_To_File.csv"
$users | % {
$_.Group
}

Related

Directory Object Not Found - Active Directory - Inputting from CSV

hi there im trying to import user accounts from a CSV file to Active Directory but i've been trying for hours to no avail. Basically I have the CSV file i want to import. So I've been trying multiple powershell scripts and getting the same error
CSV contents:
GivenName,Surname,Name,SamAccountName,Path,userPrincipalName
Scooby,Doo,Scooby,Scooby,"OU=Vehicles,OU=Production,DC=csc,DC=local",scooby#csc.local
Shaggy,Rogers,Shaggy,Shaggy,"OU=Vehicles,OU=Production,DC=csc,DC=local",shaggy#csc.local
Fred,Jones,Fred,Fred,"OU=Weapons,OU=Production,DC=csc,DC=local",fred#csc.local
Daphne,Blake,Daphne,Daphne,"OU=Weapons,OU=Production,DC=csc,DC=local",daphne#csc.local
Velma,Dinkley,Velma,Velma,"OU=Weapons,OU=Production,DC=csc,DC=local",velma#csc.local
Pat,Pending,Pat,Pat,"OU=Biological,OU=Research,DC=csc,DC=local",pat#csc.local
Red,Max,Red,Red,"OU=Biological,OU=Research,DC=csc,DC=local",red#csc.local
Peneolope,Pitstop,Peneolope,Peneolope,"OU=Biological,OU=Research,DC=csc,DC=local",peneolope#csc.local
Peter,Perfect,Peter,Peter,"OU=Energy,OU=Research,DC=csc,DC=local",peter#csc.local
Rock,Slag,Rock,Rock,"OU=Energy,OU=Research,DC=csc,DC=local",rock#csc.local
Gravel,Slag,Gravel,Gravel,"OU=Energy,OU=Research,DC=csc,DC=local",gravel#csc.local
Luke,Bear,Luke,Luke,"OU=Energy,OU=Research,DC=csc,DC=local",luke#csc.local
Rufus,Ruffcut,Rufus,Rufus,"OU=Energy,OU=Research,DC=csc,DC=local",rufus#csc.local
Dick,Dastardly,Dick,Dick,"OU=Energy,OU=Research,DC=csc,DC=local",dick#csc.local
Rick,Sanchez,Rick,Rick,"OU=Board,OU=Management,DC=csc,DC=local",rick#csc.local
Morty,Smith,Morty,Morty,"OU=Board,OU=Management,DC=csc,DC=local",morty#csc.local
Beth,Smith,Beth,Beth,"OU=HR,OU=Management,DC=csc,DC=local",beth#csc.local
Powershell Script:
#Enter a path to your import CSV file
$ADUsers = Import-csv C:\scripts\csc.csv
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
#Check if the user account already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, output a warning message
Write-Warning "A user account $Username has already exist in Active Directory."
}
else
{
#If a user does not exist then create a new user account
#Account will be created in the OU listed in the $OU variable in the CSV file; don’t forget to change the domain name in the"-UserPrincipalName" variable
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#csc.local" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword $Password `
}
}
Output from powershell:
New-ADUser : Directory object not found
At C:\scripts\Add-NewUsers.ps1:24 char:25
+ New-ADUser <<<< `
+ CategoryInfo : ObjectNotFound: (CN=Rick Sanchez...DC=csc,DC=local:String) [New-ADUser], ADIdentityN
undException
+ FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.NewADUser
this error is repeated 7 times or so but the only thing different is the name (where is says ObjectNotFound(CN=Rick Sanchez..) different name for each error
Try adding this try catch block to your code, according to some googling this error is related to the OU where you want to create the new users not existing.
$ErrorActionPreference = 'Stop'
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
try
{
Get-ADOrganizationalUnit $OU
}
catch
{
"Creating OU: $OU"
$name, $path = $OU.Split(',',2)
New-ADOrganizationalUnit -Name $name.Replace('OU=','') -Path $path
}
# Continue script here
}
Unrelated but, you might also want to consider start using splatting on your code for obvious reasons:
$params = #{
SamAccountName = $Username
UserPrincipalName = "$Username#csc.local"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $True
ChangePasswordAtLogon = $True
DisplayName = "$Lastname, $Firstname"
Path = $OU
AccountPassword = $Password
}
New-ADUser #params

Check for duplicate - ADUsers in bulk

I am trying to make a PowerShell script to add users in bulk through a csv file. If the username already exists I want to add the number 1 to the username. How can I do this? I thought I could maybe make an if?
foreach ($User in $ADUsers) {
# Selvlagde variabler for opprettelse av brukere
$Password = Get-RandomCharacters -length 20 -characters 'ABCDEFGHKLMNOPRSTUVWXYZabcdefghiklmnoprstuvwxyz1234567890!._?/-'
$Username = $User.GivenName.substring(0,3) + $User.SurName.substring(0,3)
$Username = $Username.Replace('æ','ae')
$Username = $Username.Replace('ø','o')
$Username = $Username.Replace('å','aa')
$Username = $Username.ToLower()
$Username = $Username.Trim()
$Email = $Username + '#ONPremiumIT.com'
$DisplayName = $User.GivenName + ' ' + $User.SurName
if (condition) {
}
# Bruker splatting for å lagre info om brukere
$userParams = #{
Path = $User.Path
SamAccountName = $Username
UserPrincipalName = $Email
Name = "$($User.GivenName) $($User.SurName)"
GivenName = $User.GivenName
Surname = $User.SurName
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = $Displayname
Department = $Department
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
}
New-ADUser #userParams
You can do that by testing if a user with that SamAccountName already exists. Something like this:
foreach ($User in $ADUsers) {
# Selvlagde variabler for opprettelse av brukere
$Password = Get-RandomCharacters -length 20 -characters 'ABCDEFGHKLMNOPRSTUVWXYZabcdefghiklmnoprstuvwxyz1234567890!._?/-'
$Username = $User.GivenName.substring(0,3) + $User.SurName.substring(0,3)
$Username = $Username.Replace('æ','ae')
$Username = $Username.Replace('ø','o')
$Username = $Username.Replace('å','aa')
$Username = $Username.ToLower()
$Username = $Username.Trim()
# test if a user with that SamAccountName already exists, add an index number if needed
$n = 1 # start index at 1
$newName = $Username # copy to a new variable
while ($true) { # start an endless loop
$usr = Get-ADUser -Filter "SamAccountName -eq '$newName'" -ErrorAction SilentlyContinue
if (!$usr) {
$Username = $newName # assign the $Username variable the unique value
break # exit the loop if the $username is unique in the domain
}
# construct a new username by adding the index to it
$newName = '{0}{1}' -f $Username, $n++
}
$Email = $Username + '#ONPremiumIT.com'
$DisplayName = $User.GivenName + ' ' + $User.SurName
# Bruker splatting for å lagre info om brukere
$userParams = #{
Path = $User.Path
SamAccountName = $Username
UserPrincipalName = $Email
Name = "$($User.GivenName) $($User.SurName)"
GivenName = $User.GivenName
Surname = $User.SurName
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = $Displayname
Department = $Department
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
}
New-ADUser #userParams
}
P.S. The test for the username must come before doing more things with the $Username variable, like using it for the $Email variable. Otherwise, you could have duplicates in that too..

student multi add user script, broken filter on get-aduser

hi just student trying to Bulk add Users from a .csv
when using this, its breaking at the User Filter, but I'm unsure why
error says this line is the issue
" if (Get-ADUser -F { sAMAccountName -eq $username })
Get-ADUser: The search filter cannot be recognized"
i think the csv import is fine but I'm new to this so not really sure what causing the filter to break
$ADUsers = Import-csv 'Path'
#$apiRequest = Get-Content -Raw -Path path.json | ConvertFrom-Json
foreach ($User in $ADUsers) {
$firstName = $user.FirstName
$surname = $user.Surname
$branch = $user.Branch
$city = $user.City
$country = $user.Country
$company = $user.CompanyName
$countryCode = $user.CountryCode
$email = $user.Email
$userType = $User.UserType
$vaildUsernameFormat = "[^a-zA-Z_]" # anything that's _not_ a-z or underscore
$username = ($firstName.$surname) -replace $vaildUsernameFormat, '' #removes anything that isn't a-z
$ou = $User.ou
#Check if the user account already exists in AD
if (Get-ADUser -F { sAMAccountName -eq $username }) {
#If user does exist, output a warning message
Write-Warning "A user account $username has already exist in Active Directory."
}
else {
#If a user does not exist then create a new user account
New-ADUser `
-co $country
-company $company
-countryCode $countryCode
-department $department
-displayName $username
-sn $surname
-st $streetName
-title $title
}
}
thanks for anything you can offer
full error message is
Get-ADUser : The search filter cannot be recognized
At "path" csv.ps1:41 char:13
+ if (Get-ADUser -F { sAMAccountName -eq $username }) {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Add Multiple Users To AD, CSV

I'm attempting to import users via a CSV folder.
I have certain parameters that need to be kept, so I'm only using certain fields.
Powershell
$csv = Import-Csv -Path "newusers.csv"
foreach ($User in $csv)
{
#region Data Generation
$DisplayName = $User.'Surname' + " " + $User.'GivenName'
$Mail = $User.'GivenName' + "." + $User.'Surname' + "#" + "royalberkshire.nhs.uk"
$MailAlias = $User.'GivenName' + "." + $User.'Surname' + "#" + $DNSRoot2
$SInitial = $User.'Surname'[0]
$Initial = $User.'GivenName'[0]
$SAMAccountName = $User.'Surname' + "" + $Initial
$SAMAccountLower = $SAMAccountName.ToLower()
$UserPrincipalName = $User.'Surname'+$Initial
$HD = "U"
$HDir = "\\RBHFILRED002\"
$AC = "Users_01$\"
$DH = "Users_02$\"
$IM = "Users_03$\"
$NS = "Users_04$\"
$TZ = "Users_05$\"
$Folder = if ($SInitial -in 'a','b','c'){$AC}
ElseIf ($SInitial -in 'd','e','f', 'g','h'){$DH}
ElseIf ($SInitial -in 'i','j','k', 'l','m'){$IM}
ElseIf ($SInitial -in 'n','o','p', 'q','r','s'){$NS}
Else {$TZ}
$group1 = "zz Everyone"
$group2 = "Safeboot Domain Users"
$defaultname = $SAMAccountName
$email = $User.'GivenName' + "." + $User.'Surname'
$i = 1
cls
# Create The User
While ((Get-ADUser -Filter "SamAccountName -eq '$SAMAccountName'" -ErrorAction SilentlyContinue) -ne $null){
$SamAccountName = $defaultname + [string]$i
$Mail = $email + [string]$i + "#" + "royalberkshire.nhs.uk"
$i++
}
$NewUserParams = #{
path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
SamAccountName = $SAMAccountName
Name = $SAMAccountName
DisplayName = $DisplayName
GivenName = $User.'GivenName'
Surname = $User.'Surname'
EmailAddress = $Mail
UserPrincipalName = "$SAMAccountName#rbbh-tr.nhs.uk"
Title = $title
HomeDrive = $HomeDrive
HomeDirectory = "$HDir$Folder$SAMAccountName"
Description = $User.'Description'
ChangePasswordAtLogon = $true
PasswordNeverExpires = $false
AccountPassword = $password
Enabled = $true
}
New-ADUser #NewUserParams -ErrorAction SilentlyContinue
Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
Start-Sleep -s 10
Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
cls
echo "Please Wait Whilst We Create The AD Account & Create The Exchange Mailbox.."
Start-Sleep -s 30
Enable-Mailbox -Identity $SAMAccountName
cls
echo "Please Wait Whilst We Activate The Exchange Mailbox..."
Start-Sleep -s 15
# Sets The User Up With The Randomised Password, And Re-Encrypts It For Double Protection
Set-ADAccountPassword -Identity $SAMAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $random -Force)
cls
}
CSV
User GivenName Surname Description
User James Timms Test
User James Timms Test
User Hulk Hogan Test
User Ultimate Warrior Test
User The Rock Test
User Dwayne Johnson Test
The script does not run. It tells me that the Search Filter Cannot Be Recognized.
It just errors on me.
It works with a single user fine using Write-Hosts and Inputs.
However with the CSV it doesn't work.
I must note, this is also the first time I've created users via a CSV on powershell.
Does anybody have any idea on how to fix this issue?
I got it working,
Turns out when I was building the CSV within Excel 2016 it wasn't adding the commas to seperate values.
I ended up opening the CSV within notepad and added commas to separate the values.
Powershell reads the Values based on Comma Seperation, so if there are no commas, it doesn't know what values to push out.

AD Account Will Not Create If Duplicate First Name & Second Name

I am creating a script to create users on a domain for one of my clients (NHS in the UK), however it currently refuses to create the AD User & exchange account if the user has a First & Second Name that Already Exists within the AD.
I have already bypassed username duplication by adding a number onto the end of the usernames if they already exist. However, if the first / second name is duplicated it will not create the account.
$DisplayName = $Surname + " " + $GivenName
$Mail = $GivenName + "." + $Surname + "#" + "royalberkshire.nhs.uk"
$MailAlias = $GivenName + "." + $Surname + "#" + $DNSRoot2
$SInitial = $Surname[0]
$Initial = $GivenName[0]
$SAMAccountName = $Surname + "" + $Initial
$SAMAccountLower = $SAMAccountName.ToLower()
$UserPrincipalName = $Surname+$Initial
$HD = "U"
$HDir = "\\RBHFILRED002\"
$AC = "Users_01$\"
$DH = "Users_02$\"
$IM = "Users_03$\"
$NS = "Users_04$\"
$TZ = "Users_05$\"
$Folder = if ($SInitial -in 'a','b','c'){$AC}
elseif ($SInitial -in 'd','e','f', 'g','h'){$DH}
elseif ($SInitial -in 'i','j','k', 'l','m'){$IM}
elseif ($SInitial -in 'n','o','p', 'q','r','s'){$NS}
else {$TZ}
$group1 = "zz Everyone"
$group2 = "Safeboot Domain Users"
$defaultname = $SAMAccountName
$email = $GivenName + "." + $Surname
$i = 1
cls
while ((Get-ADUser -Identity $SAMAccountName -ErrorAction SilentlyContinue) -ne $null) {
$SamAccountName = $defaultname + [string]$i
$Mail = $email + [string]$i + "#" + "royalberkshire.nhs.uk"
$i++
}
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
SamAccountName = $SAMAccountName
Name = $DisplayName
DisplayName = $DisplayName
GivenName = $GivenName
Surname = $Surname
EmailAddress = $Mail
UserPrincipalName = "$SAMAccountName#rbbh-tr.nhs.uk"
Title = $title
HomeDrive = $HomeDrive
HomeDirectory = "$HDir$Folder$SAMAccountName"
Description = $Description
ChangePasswordAtLogon = $true
PasswordNeverExpires = $false
AccountPassword = $defpassword
Enabled = $true
}
New-ADUser #NewUserParams
Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
Start-Sleep -s 10
Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
cls
echo "Please Wait Whilst We Find The AD Account & Create The Exchange Mailbox.."
Start-Sleep -s 30
Enable-Mailbox -Identity $SAMAccountName
cls
Any Ideas?
EDIT 1 - Error output:
Name : Microsoft.Exchange.Management.PowerShell.E2010
PSVersion : 1.0
Description : Admin Tasks for the Exchange Server
Name : Microsoft.Exchange.Management.Powershell.Support
PSVersion : 1.0
Description : Support Tasks for the Exchange Server
This tool is to be used for creating User Accounts for the RBFT Domain under
Ultima Business Solutions only. If this applies, please hit any key to continue.
Get-ADUser : Cannot find an object with identity: 'TimmsJ1' under: 'DC=rbbh-tr,DC=nhs,DC=uk'. At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:140 char:9
+ While ((Get-ADUser -Identity $SAMAccountName -ErrorAction SilentlyCon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : Cannot find an object with identity: 'TimmsJ1' u nder: 'DC=rbbh-tr,DC=nhs,DC=uk'.,Microsoft.ActiveDirectory.Management.Comm ands.GetADUser
New-ADUser : An attempt was made to add an object to the directory with a name that is already in use At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:166 char:1
+ New-ADUser #NewUserParams
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Timms James,...tr,DC=nhs,DC=uk:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : An attempt was made to add an object to the dire ctory with a name that is already in use,Microsoft.ActiveDirectory.Managem ent.Commands.NewADUser
Add-ADGroupMember : Cannot find an object with identity: 'TimmsJ1' under: 'DC=rbbh-tr,DC=nhs,DC=uk'.
At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:167 char:1
+ Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADPrincipal) [Add-ADGro upMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Micros oft.ActiveDirectory.Management.Commands.AddADGroupMember
Add-ADGroupMember : Cannot find an object with identity: 'TimmsJ1' under:
'DC=rbbh-tr,DC=nhs,DC=uk'. At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:169 char:1
+ Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
Please Wait Whilst We Find The AD Account & Create The Exchange Mailbox..
Enable-Mailbox : The operation couldn't be performed because object 'TimmsJ1' couldn't be found on 'rbhdc8red002.rbbh-tr.nhs.uk'.
At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:175 char:1
+ Enable-Mailbox -Identity $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (0:Int32) [Enable-Mailbox], Manage mentObjectNotFoundException
+ FullyQualifiedErrorId : 637D7B43,Microsoft.Exchange.Management.Recipient Tasks.EnableMailbox
Username:
TimmsJ1
Password:
Welcome123
Email:
James.Timms1#royalberkshire.nhs.uk
Job Title - Department:
Test - Ultima
Home Directory:
\\RBHFILRED002\Users_05$\TimmsJ1
You will need to manually set the new user's group memberships. Please Do This
Before Sending The User's Account Details.
Press Any Key To Close
The parameter -Name sets not only the attribute name but also cn (common name), which must be unique just like sAMAccountName. To fix the issue change this:
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
SamAccountName = $SAMAccountName
Name = $DisplayName
DisplayName = $DisplayName
...
}
into this:
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
Name = $SAMAccountName
DisplayName = $DisplayName
...
}
When omitting -SamAccountName the value of the parameter -Name is automatically assinged as the sAMAccountName too.