Link to home
Create AccountLog in
Active Directory

Active Directory

--

Questions

--

Followers

Top Experts

Avatar of Thomas Anthony
Thomas Anthony🇺🇸

Powerscript throws errors importing AD users
We have a new PS that we want to use to import AD users to our server from a CSV. We have a school where we have constant influx of users that need to be updated.
I think we have this as close as we can but we are getting errors that I can't put my finger on. May we get some help with this?

I have broken the following in three sections.
PowerScript
Errors
CSV file that we are importing

Powerscript
# Import active directory module for running AD cmdlets
Import-Module activedirectory
 
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv C:\inetpub\ftproot\bulk_users1.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
            
    $Firstname       = $User.firstname
      $Lastname       = $User.lastname      
    $Username       = $User.username
      $Password       = $User.password
      $OU             = $User.ou #This field refers to the OU the user account is to be created in
   
      #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 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 "$Username@AZC.local" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Lastname, $Firstname" `
            -Path $OU `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $False
           
      }
}
_____________________________________________________________________________________________________________________

Error

PS C:\Users\Administrator\Desktop> C:\Users\Administrator\Desktop\bulk_users1.ps1
New-ADUser : Directory object not found
At C:\Users\Administrator\Desktop\bulk_users1.ps1:29 char:3
+         New-ADUser `
+         ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=Robert Maxfi...DC=AZC,DC=local:Str
   ing) [New-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Manage
   ment.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.N  
  ewADUser
 
New-ADUser : Directory object not found
At C:\Users\Administrator\Desktop\bulk_users1.ps1:29 char:3
+         New-ADUser `
+         ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=Marcelino Or...DC=AZC,DC=local:Str
   ing) [New-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Manage
   ment.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.N  
  ewADUser
 
New-ADUser : Directory object not found
At C:\Users\Administrator\Desktop\bulk_users1.ps1:29 char:3
+         New-ADUser `
+         ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=Nickolas Bir...DC=AZC,DC=local:Str
   ing) [New-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Manage
   ment.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.N  
  ewADUser
_______________________________________________________________________________________________________________

CSV File
firstname      lastname      username      password      ou
Robert      Maxfield      rmaxfield      vbaTFt8v      CN=User,OU=Restricted Users,OU=AZC,DC=AZC,DC=local
Marcelino      Ornelas      mornelas      u29trASj      CN=User,OU=Restricted Users,OU=AZC,DC=AZC,DC=local
Nickolas      Birch      nbirch      umV3q8FJ      CN=User,OU=Restricted Users,OU=AZC,DC=AZC,DC=local

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of FOXFOX🇺🇸

Please remove the ' you have in each line of that script

view attachment Removeapostrophe.jpg
Removeapostrophe.JPG

Avatar of Thomas AnthonyThomas Anthony🇺🇸

ASKER

Thanks for your reply. I am so sorry for the misprint. I copied and pasted and it must have added that. The apostrophe isn't in the actual script.

Here is the script: "see attached"
User generated image

Avatar of Thomas AnthonyThomas Anthony🇺🇸

ASKER

I stand corrected. They are in the original script. My apologies. I believe that did fix it. I will run it again in the morning with a new CSV but for now it looks like you nailed it.
Thanks so much for the keen eye and fast answer. You are amazing.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of FOXFOX🇺🇸

Nice!!

ASKER CERTIFIED SOLUTION
Avatar of oBdAoBdA

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Avatar of Thomas AnthonyThomas Anthony🇺🇸

ASKER

Thank you. We will try this today. I appreciate your work on this.

Avatar of Thomas AnthonyThomas Anthony🇺🇸

ASKER

oBDa, you nailed it perfectly. We ran your script as is and it worked perfectly. Thank you thank you thank you. It pulled in new users exactly how we needed.
May I ask one more question? Is there a way to specify and account expiration date?
And is it possible to put them as members of multiple AD domain services folder?
This is so far above me.

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Just add a column "AccountExpirationDate" to the csv and set it to the first day the account should be disabled, as yyyy-MM-dd (so if the account should work up until and including April 30, use "2020-05-01".
# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory

#Loop through each row containing user details in the CSV file
Import-Csv C:\inetpub\ftproot\bulk_users1.csv | ForEach-Object {
	Write-Host "Processing user '$($_.Username)' ..."
	#Check to see if the user already exists in AD
	If (Get-ADUser -Filter "SamAccountName -eq '$($_.Username)'") {
		Write-Warning "A user account with username $($_.Username) already exist in Active Directory."
	} Else {
		#User does not exist then proceed to create the new user account
		$splat = @{
			SamAccountName = $_.Username
			UserPrincipalName = "$($_.Username)@AZC.local"
			Name = "$($_.Firstname) $($_.Lastname)"
			GivenName = $_.Firstname
			Surname = $_.Lastname
			Enabled = $true
			DisplayName = "$($_.Lastname), $($_.Firstname)"
			Path = $_.OU
			AccountPassword = (ConvertTo-SecureString -String $_.Password -AsPlainText -Force)
			ChangePasswordAtLogon = $false
			AccountExpirationDate = $_.AccountExpirationDate
		}
		New-ADUser @splat
		Write-Host "... user created successfully."
	}
}

Open in new window

And is it possible to put them as members of multiple AD domain services folder?
Don't know what you mean with that, sorry. An AD user can not be stored in multiple OUs, if that's what you mean.

Avatar of Thomas AnthonyThomas Anthony🇺🇸

ASKER

I’m sorry. We want to add them to multiple groups. Sorry about the confusuion

Add another column "MemberOf" to the csv with a comma separated (or set a different delim in line 4) list of the SamAccountNames of the groups.
# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory

$groupDelim = ','
#Loop through each row containing user details in the CSV file
Import-Csv C:\inetpub\ftproot\bulk_users1.csv | ForEach-Object {
	Write-Host "Processing user '$($_.Username)' ..."
	# Check to see if the user already exists in AD
	If (Get-ADUser -Filter "SamAccountName -eq '$($_.Username)XXX'") {
		Write-Warning "A user account with username $($_.Username) already exist in Active Directory."
	} Else {
		# User does not exist then proceed to create the new user account
		$splat = @{
			SamAccountName = $_.Username
			UserPrincipalName = "$($_.Username)@AZC.local"
			Name = "$($_.Firstname) $($_.Lastname)"
			GivenName = $_.Firstname
			Surname = $_.Lastname
			Enabled = $true
			DisplayName = "$($_.Lastname), $($_.Firstname)"
			Path = $_.OU
			AccountPassword = (ConvertTo-SecureString -String $_.Password -AsPlainText -Force)
			ChangePasswordAtLogon = $false
			AccountExpirationDate = $_.AccountExpirationDate
		}
		New-ADUser @splat
		If ($_.MemberOf) {
			Add-ADPrincipalGroupMembership -Identity $_.Username -MemberOf $_.MemberOf.Split($groupDelim).Trim()
		}
		Write-Host "... user created successfully."
	}
}

Open in new window


Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Thomas AnthonyThomas Anthony🇺🇸

ASKER

Thanks so much for everything you did. You have been amazing.
Active Directory

Active Directory

--

Questions

--

Followers

Top Experts

Active Directory (AD) is a Microsoft brand for identity-related capabilities. In the on-premises world, Windows Server AD provides a set of identity capabilities and services, and is hugely popular (88% of Fortune 1000 and 95% of enterprises use AD). This topic includes all things Active Directory including DNS, Group Policy, DFS, troubleshooting, ADFS, and all other topics under the Microsoft AD and identity umbrella.