New-ADUser: The object name has bad syntax - powershell

I want to create a new AD user but it is showing error message like:
New-ADUser : The object name has bad syntax
At C:\Users\sa\Desktop\AD User Script.ps1:22 char:1
+ New-ADUser -Name "$displayName" -UserPrincipalName "($initials) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=fbfb regbgfn...IT,DC=,DC=it:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser
$firstName = Read-Host "Indtast dit fornavn"
$middlename = Read-Host "Indtast dit mellemnavn (Hvis du ikke har et tryk Enter)"
$surname = Read-Host "Indtast dit efternavn"
$PlainPassword = "Admin100"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
$group = Read-Host "Hvilken Gruppe? [1 - Help] [2 - Sof] [3 - In]"
$firstletter1 = $firstname.Substring(0, 1)
$secondletter = $firstname.Substring(0, 2)
$firstletter2 = $middlename.Substring(0, 1)
$firstletter3 = $surname.Substring(0, 1)
$displayName = "$firstName $middlename$surname"
if ($middlename -eq $Null) {
$initials = "$firstletter1$secondletter$firstletter3".ToLower()
Write-Host "$initials"
}
else {
$initials = "$firstletter1$firstletter2$firstletter3".ToLower()
Write-Host "$initials"
}
$Searcher = [ADSISearcher]"(sAMAccountName=$initials)"
$Results = $Searcher.FindOne()
If ($Results -eq $Null) {
If ($group -eq 1) {
New-ADUser -Name "$displayName" -UserPrincipalName "($initials)" -Path "OU=,OU=,OU-,OU=,DC=,DC=" -Enabled $true -AccountPassword $SecurePassword -ChangePasswordAtLogon $True -DisplayName "$initials" -GivenName "$firstname" -HomeDrive "P: \\fileshare\Privat\%$initials%" -Initials "$initials" -SamAccountName "$firstletter1" -Surname "$surname"
}

Can you check the UserPrincipalName and sAMAccountName formats. An example would be:
Name: John Smith
UPN: smithj#example.com
sAMAccountName : smithj
UPN Format
A UPN consists of a UPN prefix (the user account name) and a UPN suffix (a DNS domain name). The prefix is joined with the suffix using the "#" symbol. For example, "someone# example.com". A UPN must be unique among all security principal objects within a directory forest. This means the prefix of a UPN can be reused, just not with the same suffix.

Related

Directory Object Not Found - Active Directory - Inputting from CSV

hi there im trying to import user accounts from a CSV file to Active Directory but i've been trying for hours to no avail. Basically I have the CSV file i want to import. So I've been trying multiple powershell scripts and getting the same error
CSV contents:
GivenName,Surname,Name,SamAccountName,Path,userPrincipalName
Scooby,Doo,Scooby,Scooby,"OU=Vehicles,OU=Production,DC=csc,DC=local",scooby#csc.local
Shaggy,Rogers,Shaggy,Shaggy,"OU=Vehicles,OU=Production,DC=csc,DC=local",shaggy#csc.local
Fred,Jones,Fred,Fred,"OU=Weapons,OU=Production,DC=csc,DC=local",fred#csc.local
Daphne,Blake,Daphne,Daphne,"OU=Weapons,OU=Production,DC=csc,DC=local",daphne#csc.local
Velma,Dinkley,Velma,Velma,"OU=Weapons,OU=Production,DC=csc,DC=local",velma#csc.local
Pat,Pending,Pat,Pat,"OU=Biological,OU=Research,DC=csc,DC=local",pat#csc.local
Red,Max,Red,Red,"OU=Biological,OU=Research,DC=csc,DC=local",red#csc.local
Peneolope,Pitstop,Peneolope,Peneolope,"OU=Biological,OU=Research,DC=csc,DC=local",peneolope#csc.local
Peter,Perfect,Peter,Peter,"OU=Energy,OU=Research,DC=csc,DC=local",peter#csc.local
Rock,Slag,Rock,Rock,"OU=Energy,OU=Research,DC=csc,DC=local",rock#csc.local
Gravel,Slag,Gravel,Gravel,"OU=Energy,OU=Research,DC=csc,DC=local",gravel#csc.local
Luke,Bear,Luke,Luke,"OU=Energy,OU=Research,DC=csc,DC=local",luke#csc.local
Rufus,Ruffcut,Rufus,Rufus,"OU=Energy,OU=Research,DC=csc,DC=local",rufus#csc.local
Dick,Dastardly,Dick,Dick,"OU=Energy,OU=Research,DC=csc,DC=local",dick#csc.local
Rick,Sanchez,Rick,Rick,"OU=Board,OU=Management,DC=csc,DC=local",rick#csc.local
Morty,Smith,Morty,Morty,"OU=Board,OU=Management,DC=csc,DC=local",morty#csc.local
Beth,Smith,Beth,Beth,"OU=HR,OU=Management,DC=csc,DC=local",beth#csc.local
Powershell Script:
#Enter a path to your import CSV file
$ADUsers = Import-csv C:\scripts\csc.csv
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
#Check if the user account already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, output a warning message
Write-Warning "A user account $Username has already exist in Active Directory."
}
else
{
#If a user does not exist then create a new user account
#Account will be created in the OU listed in the $OU variable in the CSV file; don’t forget to change the domain name in the"-UserPrincipalName" variable
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#csc.local" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword $Password `
}
}
Output from powershell:
New-ADUser : Directory object not found
At C:\scripts\Add-NewUsers.ps1:24 char:25
+ New-ADUser <<<< `
+ CategoryInfo : ObjectNotFound: (CN=Rick Sanchez...DC=csc,DC=local:String) [New-ADUser], ADIdentityN
undException
+ FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.NewADUser
this error is repeated 7 times or so but the only thing different is the name (where is says ObjectNotFound(CN=Rick Sanchez..) different name for each error
Try adding this try catch block to your code, according to some googling this error is related to the OU where you want to create the new users not existing.
$ErrorActionPreference = 'Stop'
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
try
{
Get-ADOrganizationalUnit $OU
}
catch
{
"Creating OU: $OU"
$name, $path = $OU.Split(',',2)
New-ADOrganizationalUnit -Name $name.Replace('OU=','') -Path $path
}
# Continue script here
}
Unrelated but, you might also want to consider start using splatting on your code for obvious reasons:
$params = #{
SamAccountName = $Username
UserPrincipalName = "$Username#csc.local"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $True
ChangePasswordAtLogon = $True
DisplayName = "$Lastname, $Firstname"
Path = $OU
AccountPassword = $Password
}
New-ADUser #params

Running my poweshell script produces an error and doesn't onboard new users

I am trying to on-board users utilizing Powershell for the company I am working for, however I am coming into an issue that states the directory object is not found. Can anyone assist me with what my error is and how to fix it?
I have tried to remove the city, organizational unit and have tried editing my excel csv file several times, but all tests have failed
# 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:\Users\padmin\Documents\users.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
$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
$zipcode = $User.zipcode
$state = $User.state
$country = $User.country
$telephone = $User.telephone
$jobtitle = $User.jobtitle
$company = $User.company
$department = $User.department
$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 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#greenkeyllc.com" `
-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 `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}
Expected results is to add a user into the proper organizational unit (different office locations) within the local active directory. The actual results are the error below.
New-ADUser : Directory object not found
At C:\Users\padmin\Documents\bulk_users1.ps1:41 char:3
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (CN=Bob Jake,CN=...eenkey,DC=local:String) [New-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.NewADUser
-Company : The term '-Company' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At C:\Users\padmin\Documents\bulk_users1.ps1:51 char:13
+ -Company $company `
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-Company:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The # commented out line in the middle of the script breaks your expected line continuation:
-Path $OU `
#-City $city `
-Company $company `
Put the arguments in to a hashtable and splat them instead:
$NewADUserArgs = #{
SamAccountName = $Username
UserPrincipalName = "$Username#greenkeyllc.com"
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
AccountPassword = (convertto-securestring $Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
New-ADUser #NewADUserArgs
Now you can easily comment out a single entry in the argument table without worrying about line breaks and all those pesky backticks

Import Script for AD Powershell

I am having trouble with an import user script for Active Directory. It was working before then i added Employee ID, Address and SamAccountName now I'm receving bad syntax errors can i please get some help with this.
Script:
# Create password for users
$Password = ConvertTo-SecureString "Bevchain123$" -AsPlainText -Force
# Inputing CSV file path
$CSVlocation = Read-Host -Prompt "Enter path to CSV file"
# Puttting file into a variable
$users = Import-Csv $CSVlocation
#Create for each function to grab data from CSV file
foreach ($user in $users) {
#Frist name
$FirstName = $user.'First Name'
#Last name
$LastName = $user.'Last Name'
#description
#$Description = $user.Description
#Orginisational Unit Path
$OUpath = $user.Unit
$EmployID = $user.'Personal Number'
$Address = $user.Address
$aaccount = $user.Samaccountname
# Create the Active Directory user for each line of the CSV
NEW-ADUser -Name "$FirstName $LastName" -EmployeeID "$EmployID" -SamAccountName "$aaccount" -GivenName "$FirstName" -StreetAddress "$Address" -UserPrincipalName "$FirstName.$LastName" -AccountPassword $Password -ChangePasswordAtLogon $false -Path $OUpath
# Message output to screen
Echo "user created successfully for: $FirstName in path: $OUpath"
}
Error Message:
NEW-ADUser : The object name has bad syntax
At C:\Users\Administrator\Desktop\Scripts\Import Users.ps1:41 char:1
+ NEW-ADUser -Name "$FirstName $LastName" -EmployeeID "$EmployID" -SamA ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Brendan Week...vTest,DC=Local":String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser
CSV Format:
First Name,Last Name,Address,Personal Number,Unit,Samaccountname
Test,User01,123 Test Street,000001,"OU=TestOU,DC=TestDC,DC=Local",Tuser01
Test,User02,123 Test Street,000002,"OU=TestOU,DC=TestDC,DC=Local",Tuser02

Name provided not a properly formed account name

Can someone help with another error I'm experiencing?
My create user script is giving me another error.
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Username = $User.ID
$Password = $User.BDATE
$Firstname = $User.FNAME
$Lastname = $User.LNAME
$Department = $User.GRD
$Company = $User.SCHID #This field refers to the OU the user account is to be moved to
# Choose OU
switch ($Company)
{
"1480" {$OU = 'OU=students,OU=users,ou=hs,dc=clasd,dc=net'}
"1479" {$OU = 'OU=students,OU=users,ou=elem,dc=clasd,dc=net'}
"1480" {$Folder = '\\hs-ss\students\hs'}
"1479" {$Folder = '\\hs-ss\students\elem'}
}
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#clasd.net" `
-Name $Firstname $Lastname `
-GivenName $Firstname `
-Department "$Department" `
-Company "$Company" `
-EmailAddress "$Username#clasd.net" `
-Surname $Lastname `
-Enabled $True `
-Scriptpath "login.vbs" `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-Homedrive "Z" `
-homedirectory "$Folder\$username" `
-AccountPassword (ConvertTo-SecureString "$User.BDATE" -AsPlainText -Force) `
-ChangePasswordAtLogon $true
}
My error is:
New-ADUser : The name provided is not a properly formed account name
At C:\AD_Scripts\psscripts\user_create.ps1:34 char:9
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=\\ ,OU=stude...dc=clasd,dc=net:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : The name provided is not a properly formed account name,Microsoft.ActiveDirectory.Management.Commands.NewADUser
EDIT 1
If I Write-Host $Firstname $Lastname I get "User2 User2" which is correct.
EDIT 2
The account still gets created even with that message I receive.
Edit 3
I've gone ahead and splatted things like I've been told. I'm still struggling with the same error though. Only this time the user does NOT get created.
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv userimport.csv
#Store report in log file in the $log variable
$log = "log.txt"
#Set Additional Variables
$Password = (ConvertTo-SecureString -AsPlainText "$User.BDATE" -Force)
$DisplayName = "$User.FNAME+ ' ' + $user.LNAME"
$Company = $User.SCHID
# Choose OU
Switch ($Company)
{
"1480" {$OU = 'OU=students,OU=users,ou=hs,dc=clasd,dc=net'}
"1479" {$OU = 'OU=students,OU=users,ou=elem,dc=clasd,dc=net'}
"1480" {$Folder = '\\hs-ss\students\hs'}
"1479" {$Folder = '\\hs-ss\students\elem'}
}
Write-Host $DisplayName
#Create Hash Table for New User Creation
$ADUsers = #{
'SamAccountName' = "$User.ID"
'UserPrincipalName' = "$User.ID + '#clasd.net'"
'GivenName' = "$User.FNAME"
'SurName' = "$User.LNAME"
'EmailAddress' = "$User.ID = '#clasd.net'"
'Path' = $OU
'Department' = "$User.GRD"
'Company' = "$User.SCHID"
'AccountPassword' = $Password
'ChangePasswordAtLogon' = $true
'Enabled' = $true
'DisplayName' = "$DisplayName"
'Name' = $Displayname
}
#Call New-ADUser with the parameters Above
Foreach ($User in $ADUsers) {
New-ADUser #ADUsers}
PS C:\AD_Scripts\psscripts> .\Untitled1.ps1
CN=User2 User2,OU=Students,OU=Users,OU=Elem,DC=clasd,DC=net.FNAME+ ' ' + CN=User2 User2,OU=Students,OU=Users,OU=Elem,DC=clasd,DC=net.LNAME
New-ADUser : The name provided is not a properly formed account name
At C:\AD_Scripts\psscripts\Untitled1.ps1:48 char:1
+ New-ADUser #ADUsers}
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=CN\=User2 Us...dc=clasd,dc=net:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : The name provided is not a properly formed account name,Microsoft.ActiveDirectory.Management.Commands.NewADUser
I've updated powershell to version 4 and I no longer receive any errors in my original script that I posted. Previously I was using Ver 3

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.