There were two issues:
Add-ADGroupMember: $testStaffUsers on $RA_Groups was empty. Maybe a typo?
Move-ADObject: $Username is a string, -Identity accepts DN, GUID or derived types.
My changes prepended with ###
Give this a try:
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from .csv file in the $ADUsers variable
$ADUsers = Import-Csv 'D:\OneDrive - testit\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\RA_Test3.csv'
### Set static variables now, instead of doing it in every foreach pass
$RA_Groups = @('Chinese Staff', 'testStaffUsers', 'testUsers', 'Research Assistants')
$OU_RA = 'OU=Research Assistant,OU=Academic,OU=Staff,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn'
#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers) {
#Read user data from each field in each row and assign the data to a variable as below
$Lastname = $User.EnglishLastName
$Firstname = $User.EnglishFirstName
$department = $User.Department
$Username = $User.Account
$Password = $User.Password
$email = $User.Email
$displayname = $User.Displayname
$employeeid = $User.EmployeeID
$employeenumber = $User.EmployeeNumber
$OU = 'OU=Rachel test,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn'
$city = $User.city
$zipcode = $User.Zipcode
$jobtitle = $User.JobTitle
$company = $User.Company
$employeeType = $User.employeeType
#Check to see if the user already exists in AD
if (Get-ADUser -F { SamAccountName -eq $Username }) {
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exists in Active Directory."
}
else {
#User does not exist then proceed to create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
### Using try to make sure success Write-Output doesn't run if there's an error
try {
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$******@testit.edu.cn" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$displayname" `
-Path $OU `
-EmployeeID $employeeid `
-EmployeeNumber $employeenumber `
-City $city `
-PostalCode $zipcode `
-Title $jobtitle `
-Company $company `
-Department $department `
-EmailAddress $email `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -ChangePasswordAtLogon $True `
-OtherAttributes @{'employeeType' = $employeeType }
Write-Output "User $($Username) Created in Active Directory"
}
catch {
Write-Error $_
}
}
### Removed the inner foreach, it would reread every user, in every row of the csv
if ($jobtitle -eq 'Research Fellow (RF)') {
foreach ($RA_Group in $RA_Groups) {
try {
Add-ADGroupMember -Identity $RA_Group -Members $Username
Write-Output "User $($Username) has been added to group $($RA_Group)"
Move-ADObject -Identity $(Get-ADUser $username) -TargetPath $OU_RA
Write-Output "Moved Account $($Username) to $($OU_RA)"
}
catch {
Write-Error $_
}
}
}
}