2

My aim is to import users in a CSV file to Active Directory via a simple PowerShell Script. Despite this I'm encountering a syntax error as seen below.

Updated: CSV Column Format

name,surname,ou
Steven,Boone,Management
Rodney,Fisher,Sales
Taylor,Bautista,Management
Nathan,Morris,Management

Working and Solved: PowerShell Code

Import-Module ActiveDirectory
$ADDSUsers = Import-Csv C:\0469697M_gxt.csv

foreach ($user in $ADDSUsers) {
     $Name = $user.name + " " + $user.surname
     $OU = $user.ou
     $OUPath = "OU=$($OU),dc=intgxt,dc=allaboutfood,dc=com,dc=mt"

     #Creating New AD Users                   
     New-ADUser -Name $Name -Path $OUPath
}   

The error

New-ADUser : The object name has bad syntax
At C:\Script.ps1:9 char:5
+     New-ADUser -Name "$name" -Path "$OU"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (CN=Tyler Blair,Management:String) [New-ADUser], ADException
    + FullyQualifiedErrorId :ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser

Not sure where I have an error. As far as I'm concerned the columns are being parsed well.

Sam_M
  • 29
  • 1
  • 7
  • 4
    "*As far as I'm concerned the columns are being parsed well.*" - I'm guessing they aren't. `NotSpecified: (CN=Tyler Blair,Management:String)` says to me that the CSV parser is falling over on the OU data, which should be like `CN=Tyler Blair,OU=This,DC=example,DC=com` and your CSV doesn't have that quoted, so Import-CSV is splitting the OU up on commas as if they were different columns, and then you're creating an object without a full path and it's failing on that. A guess, because your code doesn't look incorrect. Alternately maybe the OU in your spreadsheet isn't a full path and needs to be – TessellatingHeckler Apr 27 '18 at 19:32
  • Yeah I have an ou column but not a DC column. In the error, Management is an OU but I dont know what Management:String is. What suggestions do you have @TessellatingHeckler? – Sam_M Apr 27 '18 at 19:41
  • Please post a sample of the CSV. Feel free to change names but try to keep the structure intact. Do this by editing your question not as a comment. – EBGreen Apr 27 '18 at 19:46
  • @EBGreen Updated my CSV Columns and added some data - Thanks for your help :) – Sam_M Apr 27 '18 at 19:57
  • Is your CSV pipe delimited, comma delimited, or tab delimited. Your example looks like the headers are pipe delimited (sort of) and the data is tab delimited. Your example code implies that it is comma delimited. – EBGreen Apr 27 '18 at 20:06
  • Oh that was just formatting on StackOverflow - It is indeed Comma delimited – Sam_M Apr 27 '18 at 20:12
  • @EBGreen Here is how it looks like in orginal format: name,surname,ou Steven,Boone,Management Rodney,Fisher,Sales Taylor,Bautista,Management Nathan,Morris,Management – Sam_M Apr 27 '18 at 20:14
  • Looks like the `-Path` has to be a full X.500 format path - https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps docs and https://serverfault.com/questions/581383/new-aduser-path-syntax examples – TessellatingHeckler Apr 28 '18 at 00:23
  • @TessellatingHeckler Alright so I updated the code in the original post. Say I have the domain - intgxt.allaboutfood.com.mt . How should I parse that in $Container? intgxt.allaboutfood.com.mt being the domain then with the OU's under it called: - Accounts - Managment - Sales Cheers – Sam_M Apr 28 '18 at 09:36
  • Thanks. Solved, check answers – Sam_M Apr 28 '18 at 10:39

3 Answers3

2

IMO, the piece that isn't working is the -Path variable you're supplying. You need to provide the DN (distinguishedName) of a path in active directory. Simplest way to do this is grab the DN of a user and get the parent container DN.

Something like this:

-Path 'OU=New User Accounts,OU=Users,DC=compost,DC=is,DC=smelly,DC=com'

Also, I'd advise you to get used to delimiting strings the same way every time and stick with it. Single and double quotes act differently. You don't have to delimit field names from your source .csv unless there are white spaces.

If you're using separate containers, just construct the parent path of the new user object on they fly.

$OU

A working example of that might be:

Start

    Import-Module ActiveDirectory
    $ADDSUsers = Import-Csv C:\0469697M_gxt.csv
    $Creation_PW = Read-Host -AsSecureString -Prompt "Choose a password"
    foreach ($user in $ADDSUsers) {
    $Container = "OU=$($OU),OU=Users,DC=contoso,DC=com"
    $FirstName = $user.name
    $LastName = $user.surname
    $Account_Name = "$($FirstName) $($LastName)"
    New-ADUser -ChangePasswordAtLogon $true -Enabled $true -Path $Container -GivenName $FirstName -Surname $LastName -Name $Account_Name Description $Description -AccountPassword $Creation_PW }

End

($Creation_PW should be a SecureString)

I pulled sections from a mass account creation script that I use for my organization. We do them on occasion. You can specify all sorts of attributes upon creation, depending upon your AD schema. I've left only the relevant pieces.

Hopefully, this helps

Dave
  • 36
  • 2
  • Alright so I updated the code in the original post. Say I have the domain - intgxt.allaboutfood.com.mt . How should I parse that in $Container? intgxt.allaboutfood.com.mt being the domain then with the OU's under it called: - Accounts - Managment - Sales Cheers – Sam_M Apr 28 '18 at 09:14
  • Glad you got everything working. As you guessed, the LDAP path was the key. Sorry to leave you hanging on the dangling variable. I had to sanitize my script due to where I work. I've been using the website for some time and I'm glad to be able to contribute something for others. – Dave Apr 28 '18 at 17:44
  • No problem @Dave . Also thank you for your service at helping to defend the country, Sir :) I appreciate your help a lot – Sam_M Apr 29 '18 at 21:36
0

Thank guys I managed to perfect my script and got it all working.

How I resolved the issue

As said above, I had to use X.500 path format for the script to find where to enter the users. For people having the same issues as me, here is the link which helped me along with the above: https://serverfault.com/questions/581383/new-aduser-path-syntax

I also have to use -Name rather than -GivenName , and then append $user.name and $user.surname together so that the names in the OU display as Dave Smith for example. This varies depending on your requirements.

Also, $($OU) had to be declared so that the script knows the OU for each corresponding user. (Provided in the .csv)

How to enter the right path (X.500 Path Format)

For anyone encountering the issue and stumbles upon this post.

OU > Domain Name

Dots within Domain name are separated by dc= For example:

Admin Organizational Unit in Contoso.com Domain
$OUPath = "OU=Admin,dc=Contoso,dc=com"

HR Organizational Unit in MyOrganization.co.uk Domain
$OUPath = "OU=HR,dc=MyOrganization,dc=co,dc=uk"

Import Organizational Unit in .CSV File
$OUImport = $user.ou (or whatever your ou column name is)
$OUPath = "OU=($OUImport),dc=MyOrganization,dc=co,dc=uk"

The Code

Import-module activedirectory
$ADDSUsers = Import-csv C:\0469697M_gxt.csv

write-host "Start Process"
write-host "-------------------------------------"

ForEach ($user in $ADDSUsers){
    $Name = $user.name + " " + $user.surname
    $OU = $user.ou
    $OUPath = "OU=$($OU),dc=intgxt,dc=allaboutfood,dc=com,dc=mt"

    #Creating New AD Users                   
    New-ADUser -Name $Name -Path $OUPath
}

Special thanks to (Dave)https://stackoverflow.com/users/9712731/dave and (EBGreen)https://stackoverflow.com/users/1358/ebgreen for their guidance.

Sam_M
  • 29
  • 1
  • 7
0

Import-Module ActiveDirectory

Store the data from NewUserssent.csv in the $ADUsers variable

$ADUsers = Import-Csv C:\temp\newuserssent.csv -Delimiter ";"

Define UPN

$UPN = "bostonIT.int"

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
$initials = $User.initials
$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
$description= $user.description 

# 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 exists 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 `
        -Description $description `
        -UserPrincipalName "$username@$UPN" `
        -Name "$firstname $lastname" `
        -GivenName $firstname `
        -Surname $lastname `
        -Initials $initials `
        -Enabled $True `
        -DisplayName "$lastname, $firstname" `
        -Path $OU `
        -City $city `
        -PostalCode $zipcode `
        -Country $country `
        -Company $company `
        -State $state `
        -StreetAddress $streetaddress `
        -OfficePhone $telephone `
        -EmailAddress $email `
        -Title $jobtitle `
        -Department $department `
        -AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) -ChangePasswordAtLogon $True

    # If user is created, show message.
    Write-Host "The user account $username is created." -ForegroundColor Green
}

}

Read-Host -Prompt "Press Enter to exit"

Wilson
  • 1