Creating ad user account with distinguished name - powershell

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

Related

Add users in bulk with csv file

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

Add a command at the end of the PowerShell script

I have a script that adds user to Active Directory
Import-Module activedirectory
$ADUsers = Import-csv E:\src\userlist.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou #This field refers to the OU the user account is to be created in
$email = $User.email
$streetaddress = $User.streetaddress
$city = $User.city
$postalcode = $User.postalcode
$state = $User.state
$country = $User.country
$telephone = $User.telephone
$jobtitle = $User.jobtitle
$company = $User.company
$department = $User.department
$Password = $User.Password
# check if user already existe
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "The $Username already exist."
}
else
{
#create user account in the good $OU from the csv
New-ADUser -SamAccountName $Username -UserPrincipalName "$Username#" -Name "$Firstname $Lastname" -GivenName $Firstname -Surname $Lastname -Enabled $True -DisplayName "$Lastname, $Firstname" -Path $OU -City $city -Company $company -State $state -StreetAddress $streetaddress -OfficePhone $telephone -EmailAddress $email -Title $jobtitle -Department $department -postalcode $postalcode -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $false
}
}
In the same script, I want also to have the New-ADUser command that will add the proxy address mail as below:
Set-ADUser -Identity $Username -EmailAddress $email -add {ProxyAddresses="smtp:$email"}
How can I add New-ADUser to my script?
To avoid having to create so many variables from the CSV first and mainly to not having to use the backticks in your code, I would suggest you switch to using Splatting to make the code more readable and maintainable.
You can add the proxyAddresses attribute with the New-ADUSer cmdlet using the OtherAttributes parameter, OR use Set-ADUser to add this after creating the user.
The proxyAddresses attribute is an array of strongly typed strings. That means you cannot use a 'normal' array (Object[]), because in there you can have all kind of value types, not just strings. This is why the code below casts the SMTP email address to [string[]].
I'm assuming the email address to add should be the Primary email address, so that is why I use SMTP: (all caps).
Import-Csv -Path 'E:\src\userlist.csv' | ForEach-Object {
# the '$_' automatic variable holds one record from the CSV
# for convenience create these two variables
$accountName = $_.username
# the proxyAddresses attribute is an array of STRONGLY typed strings
$proxyAddresses = [string[]]"SMTP:$($_.email)"
# check if user already exists
if (Get-ADUser -Filter "SamAccountName -eq '$accountName'") {
Write-Warning "The $accountName already exist."
}
else {
# lire les variables de chaque champs et les assigner en variables de commandes
# use Splatting
$userParams = #{
SamAccountName = $accountName
UserPrincipalName = "$accountName#yourdomain.com"
Name = '{0} {1}' -f $_.firstname, $_.lastname
DisplayName = '{0}, {1}' -f $_.lastname, $_.firstname
GivenName = $_.firstname
Surname = $_.lastname
Enabled = $true
Path = $_.ou
City = $_.city
Company = $_.company
State = $_.state
StreetAddress = $_.streetaddress
OfficePhone = $_.telephone
EmailAddress = $_.email
Title = $_.jobtitle
Department = $_.department
PostalCode = $_.postalcode
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $false
# either add the proxyAddresses here, or do it AFTER creating the new user with
# Set-ADUser -Identity $accountName -Add #{'proxyAddresses' = $proxyAddresses}
OtherAttributes = #{'proxyAddresses' = $proxyAddresses}
}
#create user account in the good $OU from the csv
New-ADUser #userParams
}
}
Hope this helps

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.

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.