PowerShell: Bulk create AD Users from CSV file
Reference
Import-csv and New-ADUser issue |
Requirement
Need to create users in AD by importing information from CSV.
Code Used
$Users = Import-Csv -Delimiter "," -Path "C:\Userlist-sn.csv" foreach ($User in $Users) { $Displayname = $User.Firstname + " " + $User.Lastname $UserFirstname = $User.Firstname $UserLastname = $User.Lastname $OU = "$User.OU" $SAM = $User.SAM $UPN = $User.Firstname + "." + $User.Lastname + "@" + $User.Maildomain $Description = $User.Description $Password = $User.Password New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false –PasswordNeverExpires $true -server domain.loc } |
CSV File Format
Firstname | Lastname | Maildomain | SAM | OU | Password | Description
User | Test01 | contoso.com | utest01 | OU=Standard Users,OU=Users,DC=domain,DC=loc | P@ssw0rd| Test User
'|' is replaced with ','
Error
New-ADUser: The object name has bad syntax.
Solution
1. Either use Single Quotes to avoid error.
- Remove -Delimiter in Import-CSV.
Working Code
$Users = Import-Csv -Path "C:\Userlist-sn.csv"
foreach ($User in $Users)
{
$Displayname = $User.Firstname + "
" + $User.Lastname
$UserFirstname = $User.Firstname
$UserLastname = $User.Lastname
$OU = "$User.OU"
$SAM = $User.SAM
$UPN = $User.Firstname + "." + $User.Lastname + "@" + $User.Maildomain
$Description = $User.Description
$Password = $User.Password
New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false –PasswordNeverExpires $true -server domain.loc
}
Or change the code as shown below:
$Users = Import-Csv -Path "C:\Userlist-sn.csv"
foreach ($User in $Users)
{
$Displayname = $User.'Firstname' + "
" + $User.'Lastname'
$UserFirstname = $User.'Firstname'
$UserLastname = $User.'Lastname'
$OU = $User.'OU'
$SAM = $User.'SAM'
$UPN = $User.'Firstname' + "." + $User.'Lastname' + "@" + $User.'Maildomain'
$Description = $User.'Description'
$Password = $User.'Password'
New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false –PasswordNeverExpires $true -server domain.loc
}
Other Languages
This article is also available in the following languages: