ERROR IN CREATING BULK USER CREATION IN AD USING POWERSHELL

Syam Kumar 0 Reputation points
2023-11-24T07:01:41.2633333+00:00

I HAVE GOT A TASK TO CREATE AROUND 150 USERS IN MY COMPANY USING POWERSHELL SCRIPT. I AM TESTING THE SCRIPT WITH 1 USER AND WHEN THE SCRIPT RUNS USER IS CREATED AND ABLE TO LOGIN ALSO. BUT SHOWING THE BELOW ERROR. I AM NOT CONFIDENT TO CREATE 150 USERS WITH THAT ERROR. PLS HELP ME. BELOW IS THE CODE AND ERROR. I WANT THESE OPTIONS ALSO...

CannotChangePassword $True 
			-PasswordNeverExpires $True

THE ERROR :

PS C:\Users\Administrator.UBS\Desktop> .\user.ps1

Get-ADUser: Variable: 'Username' found in expression: $Username is not defined.

#Store the data from Users.csv in the $Users variable
$Users = Import-csv C:\Users\administrator.UBS\Desktop\bulk.csv

#Loop through each row containing user details in the CSV file 
foreach ($User in $Users)
{
	#Read user data from each field in each row and assign the data to a variable as below
		
	$Username = $User.username
	$Password = $User.password
	$Firstname = $User.firstname
	$Lastname = $User.lastname
	$OU = $User.ou 
	$Password = $User.Password

	#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 exist."
	}
	else
	{
		#User does not exist then create the new user account
		
        #Account will be created in the OU provided by the $OU variable read from the CSV file
		$NewUser = New-ADUser `
			-SamAccountName $Username `
			-UserPrincipalName "$Username@ubs.com" `
			-Name "$Firstname $Lastname" `
			-GivenName $Firstname `
			-Surname $Lastname `
			-Enabled $True `
			-DisplayName "$Firstname$Lastname" `
			-Path $OU `
			-City $city `
			-Company $company `
			-State $state `
			-StreetAddress $streetaddress `
			-OfficePhone $telephone `
			-EmailAddress $email `
			-Title $jobtitle `
			-Department $department `
			-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force)
	#-ChangePasswordAtLogon $False
	}	
		# Check if the user was successfully created
    if ($NewUser) 
	{
        # Set properties after user creation
        Set-AdUser 
			-Identity $NewUser.SamAccountName 
			-CannotChangePassword $True 
			-PasswordNeverExpires $True
     
		else 
	{
        # Log an error message and continue to the next user
        Write-Warning "Failed to create user account for $($User.username)."
    }
	}
     
}
Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,188 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,448 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 33,946 Reputation points Microsoft Vendor
    2023-11-24T09:01:54.3133333+00:00

    Hi,

    It seems $Users has no username property. Please check the CSV file and make sure the column header is username.

    And you need to add -PassThru parameter to the New-ADUser cmdlet or it will not generate any output.

    Best Regards,

    Ian Xue


    If the Answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Rich Matheisen 45,671 Reputation points
    2023-11-24T16:56:39.99+00:00

    Here's another way to do the same thing:

    #Store the data from Users.csv in the $Users variable
    Import-Csv C:\Users\administrator.UBS\Desktop\bulk.csv |
        ForEach-Object{         #Loop through each row containing user details in the CSV file 
    		if ($_.UserName.Trim().Length -gt 0){       # check to see if username is populated
                if (Get-ADUser -Identity $_.$Username){ #Check to see if the user already exists in AD
                    #If user does exist, give a warning
                    Write-Warning "A user account with username $($_.Username) already exist."
                }
                else{
                    $usercreated = $false   # used in "Catch" block
                    $u = $_.Username        # needed for "Catch" block
                    Try{
                        #User does not exist. create the new user account
                        #Account will be created in the OU provided by the property in the CSV file
                        $NewUser = New-ADUser
                            -SamAccountName $_.Username
                            -UserPrincipalName "$($_.Username)@ubs.com"
                            -Name "$($_.Firstname) $($_.Lastname)"
                            -GivenName $_.Firstname
                            -Surname $_.Lastname
                            -Enabled $True
                            -DisplayName "$($_.Firstname)$($_.Lastname)"
                            -Path $_.OU
                            -City $city                     # Not in CSV?
                            -Company $company               # Not in CSV?
                            -State $state                   # Not in CSV?
                            -StreetAddress $streetaddress   # Not in CSV?
                            -OfficePhone $telephone         # Not in CSV?
                            -EmailAddress $email            # Not in CSV?
                            -Title $jobtitle                # Not in CSV?
                            -Department $department         # Not in CSV?
                            -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force)
                            -PassThru
                            -ErrorAction -STOP
                            #-ChangePasswordAtLogon $False
    
                            $usercreated = $true
    
                            # Set properties after user creation
                            # if the new user wasn't created this code won't be run
                            $NewUser | Set-ADUser 
                                -CannotChangePassword $True 
                                -PasswordNeverExpires $True
                                -ErrorAction STOP
                    }
                    Catch{
                        if ($usercreated){
                            Write-Warning "New user ($u) created, but setting password options failed."
                        }
                        else{
                            Write-Warning "Failed to create new user ($u)"
                        }
                    }
                }
            }
        }
    
    
    

    This assumes(!) that the variables noted in the code have been defined elsewhere. If that's not true, and they're data present in the CSV, replace the variable name with the "$_.<CSVColumnName>".

    0 comments No comments