Add users in bulk with csv file - powershell

I am trying to make a script that creates users in bulk from a csv file. I tested the script with 5 users, but get the error message "New-ADUser: A value for the attribute was not in the acceptable range of values." I have been searching everywhere, but can't find the mistake!
function Get-RandomCharacters($length, $characters) {
$random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
$private:ofs=""
return [String]$characters[$random]
}
$ADUsers = Import-csv C:\Users\Admin\Users.csv -Delimiter ";"
foreach ($User in $ADUsers)
{
$Password = Get-RandomCharacters -length 20 -characters 'ABCDEFGHKLMNOPRSTUVWXYZabcdefghiklmnoprstuvwxyz1234567890!._?/'
$Username = $User.GivenName.substring(0,3) + $User.SurName.substring(0,3)
$Username = $Username.Replace('æ','ae')
$Username = $Username.Replace('ø','o')
$Username = $Username.Replace('å','aa')
$Username = $Username.ToLower()
$Username = $Username.Trim()
$Email = $Username + '#ONPremiumIT.com'
$DisplayName = $User.GivenName + ' ' + $User.SurName
New-ADUser `
-Path $User.Path `
-SamAccountName $Username `
-UserPrincipalName $Email `
-Name "$User.GivenName $User.SurName" `
-GivenName $User.GivenName `
-Surname $User.SurName `
-Enabled $True `
-ChangePasswordAtLogon $false `
-DisplayName "$Displayname" `
-Department $Department `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
csv file:
GivenName;SurName;Department;Path
Tobias;Santelmann;it-drift;OU=it-drift,OU=onprit-brukere,DC=sec,DC=core
Maria;Aas;dev-team;OU=dev-team,OU=onprit-brukere,DC=sec,DC=core
Anniken;Arildset;renhold;OU=renhold,OU=onprit-brukere,DC=sec,DC=core
Thea;Urne;regnskap;OU=regnskap,OU=onprit-brukere,DC=sec,DC=core
Marthea;Wichstad;hr;OU=hr,OU=onprit-brukere,DC=sec,DC=core

The error comes from -Name "$User.GivenName $User.SurName", which should have been -Name "$($User.GivenName) $($User.SurName)".
Example:
"$User.GivenName $User.SurName" # --> #{GivenName=Tobias; Surname=Santelmann}.GivenName #{GivenName=Tobias; Surname=Santelmann}.SurName
but when using the Subexpression operator $(..), it does what you want:
"$($User.GivenName) $($User.SurName)" # --> Tobias Santelmann
Also, when using lots of parameters, you can have difficult to spot errors when using those backticks.
I'd suggest using Splatting for that:
$userParams = #{
Path = $User.Path
SamAccountName = $Username
UserPrincipalName = $Email
Name = '{0} {1}' -f $User.GivenName, $User.SurName # or: "$($User.GivenName) $($User.SurName)"
GivenName = $User.GivenName
Surname = $User.SurName
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = $Displayname
Department = $Department
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
}
New-ADUser #userParams

Related

Mass add users AD with Powershell

Import-Module ActiveDirectory
$file = "C:\Users\Administrator\Documents\UsersHR.csv"
$targetDN = "OU=HR,OU=NTTLab,DC=NTTLab,DC=internal"
$importedUsers = Import-Csv $file
foreach ($user in $importedUsers)
{
$Username = $User.Username
$Password = $User.Password
$Firstname = $User.Firstname
$Lastname = $User.Surname
$Name = $User.Firstname + $User.Lastname
$OU = "OU=HR,OU=NTTLab,DC=NTTLab,DC=internal"
$company = $User.company
$department = $User.department
$Password = $User.Password
New-ADUser -SamAccountName $Username -Name $Name -GivenName $Firstname -Surname $Lastname -Enabled $true -DisplayName "$Lastname, $Firstname" -Path $OU -Company $Company -Department $department -AccountPassword $Password -ChangePasswordAtLogon $true
}
I'm working on a VM of windows server 2016.
I'm trying to add several users at once to the AD using PowerShell ISE, but I'm running into several errors about the name.
it's either not properly formed, empty or it's asking for it manually
You didn't say what it's complaining about, but I assume it's this:
$Username = $User.Username
...
New-ADUser -SamAccountName $Username
There are several User Naming Attributes in Active Directory. The sAMAccountName attribute is a short username. It must be 20 characters or less. Although the # character is technically allowed, it is usually never used. In fact, AD Users and Computers won't let you put an # in it.
That "Username" you have in your file is a better fit for the userPrincipalName attribute.
But you will still have to figure something out for the sAMAccountName. Our organization uses the last name (cropped at 18 characters) and first two letters of the first name. That would look something like this:
Import-Module ActiveDirectory
$file = "C:\Users\Administrator\Documents\UsersHR.csv"
$targetDN = "OU=HR,OU=NTTLab,DC=NTTLab,DC=internal"
$importedUsers = Import-Csv $file
foreach ($user in $importedUsers)
{
$SamAccountName = "$($User.Surname.Substring(0, [System.Math]::Min(18, $User.Surname.Length)))$($User.Firstname)"
$UserPrincipalName = $User.Username
$Password = $User.Password
$Firstname = $User.Firstname
$Lastname = $User.Surname
$Name = "$($User.Firstname) $($User.Surname)"
$OU = "OU=HR,OU=NTTLab,DC=NTTLab,DC=internal"
$company = $User.company
$department = $User.department
$Password = $User.Password
New-ADUser -SamAccountName $SamAccountName -UserPrincipalName $UserPrincipalName -Name $Name -GivenName $Firstname -Surname $Lastname -Enabled $true -DisplayName "$Lastname, $Firstname" -Path $OU -Company $Company -Department $department -AccountPassword $Password -ChangePasswordAtLogon $true
}
I also fixed how you defined $Name, since it didn't have a space, and you were using $User.Lastname instead of $User.Surname.

Creating ad user account with distinguished name

For the life of me, I can't figure a way to either create a new ad account with the distinguished name as firstname lastname instead of the username or modifying it afterwards.
New-ADUser -SamAccountName $UserName -Name $UserName -DisplayName $DisplayName -GivenName $FirstName -Surname $LastName -UserPrincipalName $MailAddress -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $false -Path $OU -ChangePasswordAtLogon $true -server ad.corp.com -MobilePhone $MobileNumber -OfficePhone $OfficeNumber -Title $JobTitle
$fullname = $FirstName + " " + $LastName
$distinguishedName="CN=" + $fullname + ", " + $ou
set-aduser $distinguishedName
The set-aduser returns a "directory not found" which makes sense since the distinguished name is the username.
Thanks
You can assign your newly created ADUser to a variable and set its name as follows:
$Params = #{
SamAccountName = $UserName
Name = $UserName
DisplayName = $DisplayName
GivenName = $FirstName
Surname = $LastName
UserPrincipalName = $MailAddress
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
Enabled = $False
Path = $OU
ChangePasswordAtLogon = $True
Server = 'ad.corp.com'
MobilePhone = $MobileNumber
OfficePhone = $OfficeNumber
Title = $JobTitle
PassThru = $True
}
$ADUser = New-ADUser #Params
I couldn't test this, but it should work:
$DistinguishedName = "CN=$FirstName $LastName, $OU"
$ADUser.DistinguishedName = $DistinguishedName
I actually got it to work by using the rename-adobject.
Rename-ADObject -Identity $user -NewName $fullname -server ad.corp.com

Why am I getting a "missing expression" error in my PS New-ADUser script?

The error I'm getting is "Missing expression after unary operator '-'" At line 63, char 14. So it's where the Path/OU is set, but I can't find anything wrong with it. Any help is appreciated. Thanks.
# 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:\ADMaint\NewUsers\NewUsers.csv
$Password = "Welcome01"
$OU = "ou=NewUsers,ou=Users,ou=Logins,dc=company,dc=com"
#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
$Middle = $User.middle
$Lastname = $User.lastname
$Department = $User.department
$Title = $User.title
$Office = $User.office
$Address = $User.address
$Company = $User.company
$employeeNumber = $User.employeeNumber
$employeeID = $User.employeeID
$Telephone = $User.telephone
$Pager = $User.pager
$Mobile = $User.mobile
$Fax = $User.fax
$Custom1 = $User.custom1
$Custom2 = $User.custom2
$Custom3 = $User.custom3
$Custom4 = $User.custom4
$DisplayName = "$Lastname" + ", " + "$Firstname" + " " + "$Middle"
$Username = "$lastname".ToLower() + "$firstname".substring(0,1).ToLower()
#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#vinfen.org" `
-Name $DisplayName `
-GivenName $Firstname `
-surname $Lastname `
-initials $Middle `
-department $Department `
-title $Title `
-Office $Office `
-streetAddress $Address `
-Company $Company `
-employeeNumber $EmployeeNumber `
-employeeID $EmployeeID `
-OfficePhone $Telephone `
-mobile $Mobile `
-fax $Fax `
-DisplayName $DisplayName`
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
#-OtherAttribute #{pager="$(User."pager")"; extensionAttribute1="$(User."custom1")"; extensionAttribute2="$(User."custom2")"; extensionAttribute3="$(User."custom3")"; extensionAttribute4="$(User."custom4")"} `
-ChangePasswordAtLogon $true `
-Enabled $true `
}
}
Can't verify now, but looks like there is a missing space before the ` on the previous line.
-DisplayName $DisplayName`
Multi-line commands require the space before the ` symbol.

Import-CSV for Active Directory Object Already Exists Error

I created a PowerShell script to import new AD users from a CSV file. The code is:
Import-Module ActiveDirectory
$Users = Import-Csv -Delimiter "," -Path "C:\temp\kindergarten.csv"
$Password = 000
foreach ($User in $Users) {
$Password = $Password + 1
$OU = "OU=KCenter,OU=Students,OU=District Users New,DC=,DC=k12,DC=ny,DC=us"
$UserFirstname = $User.FirstName
$UserLastname = $User.LastName
$DetailedName = $UserFirstname + " " + $UserLastname
$FirstLetterFirstname = $UserFirstname.substring(0,1)
$SAMName = $FirstLetterFirstname + $UserLastname
$UserPrincipalName = $SAMName + "#student.pobschools.org"
$Description = "Kindergarteners K-Center"
New-ADUser -Name $DetailedName -SamAccountName $SAMName -UserPrincipalName $UserPrincipalName -DisplayName
$SAMName -GivenName $UserFirstname -Surname $UserLastname -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force)
-Enabled $false -Description $Description -EmailAddress $UserPrincipalName -CannotChangePassword $true -ChangePasswordAtLogon $false -Path $OU
}
The script worked for about half of the entries in the CSV. For the others I get the error:
New-ADUser : The object already exists
At C:\users\jbaruch\desktop\getADUsers.ps1:16 char:12
+ New-ADUser <<<< -Name $DetailedName -SamAccountName $SAMName -UserPrincipalName $UserPrincipalName -DisplayName
$SAMName -GivenName $UserFirstname -Surname $UserLastname -AccountPassword (ConvertTo-SecureString $Password -AsPlainTe
xt -Force) -Enabled $false -Description $Description -EmailAddress $UserPrincipalName -CannotChangePassword $true -Chan
gePasswordAtLogon $false -Path $OU
+ CategoryInfo : NotSpecified: (CN=Shradha Sang...k12,DC=ny,DC=us:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : The object already exists,Microsoft.ActiveDirectory.Management.Commands.NewADUser
If I search for the users I get an error for there are no results. I am not sure why it is coming back as already existing. Any help would be appreciated, Thanks.
Reading your comment I think this might help you:
$VerbosePreference = 'Continue'
$Users = Import-Csv -Delimiter "," -Path "C:\temp\kindergarten.csv"
$Password = 000
foreach ($User in $Users) {
$Password = $Password + 1
$SamAccountName = $User.FirstName[0] + $User.LastName
if ($U = Get-ADUser -Filter {SamAccountName -eq $SamAccountName}) {
Write-Verbose "SamAccountName $($SamAccountName) already present"
if ($U.GivenName -eq $User.FirstName) {
Write-Verbose "User firstname $($User.FirstName) already present in AD"
Continue # to the next user
}
$SamAccountName = $User.FirstName[1] + $User.LastName
Write-Verbose "New SamAccountName generated $($SamAccountName)"
}
$ADParams = #{
Name = $UserFirstname + ' ' + $UserLastname
SamAccountName = $SamAccountName
UserPrincipalName = $SamAccountName + '#student.pobschools.org'
DisplayName = $SamAccountName
GivenName = $User.FirstName
Surname = $User.LastName
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
Enabled = $false
Description = 'Kindergarteners K-Center'
EmailAddress = $SamAccountName + '#student.pobschools.org'
CannotChangePassword = $true
ChangePasswordAtLogon = $false
Path = 'OU=KCenter,OU=Students,OU=District Users New,DC=,DC=k12,DC=ny,DC=us'
}
Write-Verbose "Create user $($SamAccountName)"
New-ADUser #ADParams
}
Splatting is a nice technique for this to make things more readable.

New-Aduser : The object name has bad syntax

I have a script which i use to create bulk users from a csv file which works fine.
Import-Csv e:\temp\newemps.csv | %{
$ou = $_.ou
$firstname = $_.first
$lastName = $_.last
$accountName = $("{0}{1}" -f $firstname.Substring(0,1),$lastName).ToLower()
$description = $_.desc
$password = "Welcome1"
$name = "$firstName $lastName"
New-AdUser -SamAccountName $accountName -GivenName $firstName -UserPrincipalName "$accountName#ba.net" -Surname $lastName -DisplayName $name -Name $name -AccountPassword (ConvertTo-SecureString -AsPlainText $password -Force) -Enabled $true -Path $ou -Description $description -ChangePasswordAtLogon:$False
If ($_.Group -ne ""){
Add-adgroupmember -identity $_.group -members $accountName
}
If ($_.email -eq "y"){
Enable-Mailbox -Identity $accountName -Alias $accountName
Set-Mailbox $accountName -MaxSendSize 10mb -MaxReceiveSize 10mb
Get-CasMailbox $accountName -OwaEnabled:$false -ActiveSyncEnabled:$false
}
}
I was trying modify this script so that i could create some generic accounts that would not follow our typical convention. The input is a here-string as supposed to a csv as the only unique item is an Airport code. I have shortened the here-string for brevity.
$bases = #"
YAB
YEK
YYH
YHI
"#
$bases.Split("`n") | %{
$ou = "CN=Users,DC=BA,DC=NET"
$firstname = "$_".ToString()
$lastName = "Counter"
$accountName = "$_" + "Counter"
$description = "Base Front Counter"
$password = "Welcome1"
$name = "$firstName $lastName"
New-AdUser -SamAccountName $accountName -GivenName $firstName -UserPrincipalName "$accountName#ba.net" -Surname $lastName -DisplayName $name -Name $name -AccountPassword (ConvertTo-SecureString -AsPlainText $password -Force) -Enabled $true -Path $ou -Description $description -ChangePasswordAtLogon:$False
}
There is something about using a here-string that I am not accounting for. The only account it successfully creates is the one for YHI (The last one of the here-string). For all others it gives New-AdUser : The object name has bad syntax. Internet research shows many errors for csv-imports where the data has whitespace and other issues there but im not sure what the issue is here.
In the end I just made a csv file instead of using the here-string but I would like to know what i was doing wrong.
This worked for me. got rid of the null values and the new line values and just gave me each string value from each line. Seams there may have been some white space or some other characters that interfere if you just do split "`n"
$test = #"
user1
user2
user3
"#
$test.split(“`r`n”) | ForEach-Object {if($_){get-aduser $_}}