Powershell issue when creating new user then give them group and move to specific OU

Eaven HUANG 2,191 Reputation points
2022-08-24T01:54:35.973+00:00

Dear experts,

I'm quite new to PowerShell and still at entry-level. I'm running into an issue with my script and hope to seek some help here.
The objective I wanted to achieve is:
Create new users from .csv where their attribute values are filled
bases on their jobtitle: Add different groups, move the user to different OU

My script did work with user account creation and adding groups, but after I added the OU moving part, it failed
I'm attaching my script here and the error message, any advice would be really really helpful!!
Thank you very much in advance.

# 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'  
  
#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  
		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}  
     }  
  
  
        $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"  
  
  
        ForEach ($ADUser in $ADUsers)   
        {  
         if($jobtitle -eq 'Research Fellow (RF)'){  
                foreach($RA_Group in $RA_Groups){  
                Add-ADGroupMember -Identity $RA_Group -Members $Username  
                }  
            Move-ADObject -Identity $Username -TargetPath $OU_RA  
            Write-Output "Moved Account $($Username) to $($OU_RA)"  
            Write-Output "User $($Username) has been added to group $($RA_Groups)"  
         }  
        }  
}  
  
  
  
  
Add-ADGroupMember : Cannot find an object with identity: '' under: 'DC=testit,DC=edu,DC=cn'.  
At D:\OneDrive - testIT\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\New_Employee_test.ps1:88 char:17  
+ ...              Add-ADGroupMember -Identity $RA_Group -Members $Username  
+                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
    + CategoryInfo          : ObjectNotFound: (:ADGroup) [Add-ADGroupMember], ADIdentityNotFoundException  
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember  
   
Move-ADObject : Cannot find an object with identity: 'test.RA' under: 'DC=testit,DC=edu,DC=cn'.  
At D:\OneDrive - testit\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\New_Employee_test.ps1:90 char:13  
+             Move-ADObject -Identity $Username -TargetPath $OU_RA  
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
    + CategoryInfo          : ObjectNotFound: (test.RA:ADObject) [Move-ADObject], ADIdentityNotFoundException  
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.MoveADObject  
   
Moved Account test.RA to OU=Research Assistant,OU=Academic,OU=Staff,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn  
User test.RA has been added to group Chinese Staff  testUsers Research Assistants  


  
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rafael da Rocha 5,251 Reputation points
    2022-08-24T06:16:59.15+00:00

    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 $_  
                    }  
                }  
            }  
        }  
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.