Name provided not a properly formed account name - powershell

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

Related

Trying to create multiple AD users at once using CSV and Powershell. Splatting appears to be causing issues

As the title says, I'm trying to use powershell in combination with a CSV file to create multiple users at once but keep encountering an error. I have included the error and my code below. Any help in fixing this is much appreciated!
Powershell Error:
New-ADUser : The object name has bad syntax
At line:32 char:17
+ } } New-ADUser #hash
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Test User...REFORM,DC=local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Powershell Code:
$ADUsers = Import-csv EnterFilePathHere
foreach ($User in $ADUsers)
{
$Firstname = $User.firstname
$Surname = $User.surname
$Password = $User.password
$OU = $User.ou
$Description = $User.description
$Email = $User.email
$Username = -join("$Firstname", "_", "$Surname")
$hash = #{
SamAccountName = $Username
UserPrincipalName = "$Username#EnterDomainHere"
Name = "$($User.firstName) $($User.surName)"
givenName = $FirstName
surName = $Surname
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = "$FirstName $Surname"
Path = $OU
Description = $Description
EmailAddress = $Email
AccountPassword = (ConvertTo-SecureString "$Password" -AsPlainText -Force)
} New-ADUser #hash
}
As mentioned by theo, New-ADUser #hash is currently outside of the loop. Frustratingly, when I move it up a line (as I now have in the code displayed above) I am faced with another error:
At line:32 char:15
+ } New-AdUser #hash }
+ ~~~~~~~~~~
Unexpected token 'New-AdUser' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
Here's an example of the CSV file as displayed in Excel. The file is saved as CSV UTF-8 (Comma delimited
You should try to indent better, then you will spot the error soon enough. The New-ADUser cmdlet should be on its own separate line right below the closing bracket of the Hashtable.
Also, you don't need all those variables, just a few to make things easier
$ADUsers = Import-Csv -Path '<EnterFilePathHere>'
foreach ($User in $ADUsers) {
# for convenience create some variables that will be used more often
$Firstname = $User.firstname
$Surname = $User.surname
$Username = '{0}_{1}' -f $Firstname, $Surname
# create the splatting Hashtable
$hash = #{
SamAccountName = $Username
UserPrincipalName = "$Username#EnterDomainHere"
Name = "$Firstname $Surname"
GivenName = $FirstName
Surname = $Surname
DisplayName = "$FirstName $Surname"
Enabled = $true
ChangePasswordAtLogon = $false
Path = $User.ou
Description = $User.description
EmailAddress = $User.email
AccountPassword = (ConvertTo-SecureString $User.password -AsPlainText -Force)
}
New-ADUser #hash
}

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

How to resolve NewAD error with -Path $OU

I am currently trying to automate the creation of new users on my Active Directory.
However when I run my powershell here is the error that presents itself to me :
New-ADUser: Unable to validate argument on "Path" parameter. The argument is null or empty. Provide an argument that is not null or empty and try again.
At character Line: 23:19
+ -Path $ OR `
+ ~~~
+ CategoryInfo: InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId: ParameterArgumentValidationError, Microsoft.ActiveDirectory.Management.Commands.NewADUser
What can i do ?
Thanks for your help !
This is my code
$ADUsers = Import-csv E:\SCRIPT\newusers.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$Description = $User.description
$OU = $User.ou
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Lastname#domaine.fr" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $False `
-DisplayName "$Lastname, $Firstname" `
-Description $Description `
-AccountPassword $Password `
-Path $OU `
}
Your comment indicates the CSV file uses the ; semi-colon as delimiter character, but you neglect to add that to the Import-Csv cmdlet. Now it is trying to parse the data using the default comma , and because of that none of the fields have a correct value.
Replace the first line with
$ADUsers = Import-csv -Path 'E:\SCRIPT\newusers.csv' -Delimiter ';'
Other than that, have a look at using splatting, so you don't need those awkward backticks.

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