Avatar of andrew_2706
andrew_2706 asked on

Import Users into AD with Active Directory Module for Windows Powershell

Importing users into AD

In Active Directory Module for Windows Powershell I'm using Import-Csv .\test.csv | New-ADUser -Enabled $True -AccountPassword (ConvertTo-SecureString M5aeq -AsPlainText -force) which works to a point, I'm not getting the import of the telephonenumber and it's not placing in the Organizational Unit specified in the csv file.

givenName,name,telephonenumber,ou
test company,test company,01702 123456,OU=SarkContacts,DC=domain,DC=net

I would of preferred to import them as Contacts but I don't thing that can be done with the above method.

Regards
Mark
PowershellActive Directory

Avatar of undefined
Last Comment
andrew_2706

8/22/2022 - Mon
Mahesh

if you could upload csv and script, we can find out the issue
ASKER
andrew_2706

There is no script, it runs in Active Directory Module for Windows Powershell using the below which as I say imports the user but no telephone number and doesn't place it in the ou specified in the CSV.

Import-Csv .\test.csv | New-ADUser -Enabled $True -AccountPassword (ConvertTo-SecureString M5aeq -AsPlainText -force)

And the contents of the csv are:

givenName,name,telephonenumber,ou
test company,test company,01702 123456,OU=SarkContacts,DC=domain,DC=net
oBdA

Add two columns to the csv, SamAccountName (limited to 20 characters, should not contains spaces, unique in the domain) and UserPrincipalName.
Then use something like this (password could come individually per user from the csv as well):
$password = 'M5aeq'
Import-Csv .\test.csv | ForEach-Object {
	$ADUserArgs = @{
		SamAccountName =		$_.SamAccountName
		UserPrincipalName =		$_.UserPrincipalName
		AccountPassword =		ConvertTo-SecureString -AsPlainText $Password -Force
		Name =					$_.Name
		GivenName =				$_.GivenName
		DisplayName =			"$($_.Name), $($_.GivenName)"
		OfficePhone =			$_.telephonenumber
		ChangePasswordAtLogon = $true
		Path =					$_.OU
		Enabled =				$true
	}
	"User '$($_.SamAccountName)'" | Write-Host
	New-ADUser @ADUserArgs
}

Open in new window

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Mahesh

The cmdlet is incomplete
csv file should contains SamAccountName, given name, last name, OU location and telephone number etc with headers
Example:
csv file should contains all below fields as headers and with values

$Users = Import-Csv C:\new\users.csv

#Processing each user
Foreach ($User in $Users) {
    try {
        $saMAccountName = $user.SamAccountName

        $ADuser = Get-ADUser -LDAPFilter "(sAMAccountName=$saMAccountName)"
       
        if ($ADUser -eq $null) {
            New-ADUser -SamAccountName $saMAccountName -UserPrincipalName $($user.SamAccountName + "@domain.com") -Name ("$($user.FirstName) $($User.LastName)") -DisplayName ("$($user.FirstName) $($User.LastName)") -GivenName $user.FirstName `
            -Surname $user.LastName -Enabled $true -PasswordNeverExpires $false -AccountPassword (ConvertTo-SecureString "pass@123" -AsPlainText -Force) -ChangePasswordAtLogon $true -Path $user.TargetOU -Manager -MobilePhone $User.phone
            }
        }
catch {$error[0].ToString() }

}

Open in new window

Qlemo

AFAIK New-ADUser does not take over more than the user name or SamAccountName from pipeline, that is why everything else is ignored, and you need to run something like oBdA showed - setting properties individually in a loop.
Michelangelo

The original issue is, the CSV is not formatted correctly.
First, it uses comma as delimiter. Also, OU filed uses comma to separate its fields. You should change the csv delimiter and use the -delimiter parameter of import-csv.
New-AdUser does not have an telephonenumber parameter. Change the name to OfficePhone an it should load the value as the property is passed by name through the pipe
From: https://docs.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps

[...]
Method 3: Use the Import-Csv cmdlet with the New-ADUser cmdlet to create multiple Active Directory user objects. To do this, use the Import-Csv cmdlet to create the custom objects from a comma-separated value (CSV) file that contains a list of object properties. Then pass these objects through the pipeline to the New-ADUser cmdlet to create the user objects.
[...]
-OfficePhone
Specifies the user's office telephone number. This parameter sets the OfficePhone property of a user object. The LDAP display name (ldapDisplayName) of this property is telephoneNumber.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Qlemo

Correct, the comma delimiter is another issue of many.
I've looked up the cmdlet description now, and it accepts objects from pipeline. The properties need to be named exactly like the parameter names you would use for New-ADUser, so either add columns and change headings accordingly, or use a loop as oBdA did to map attributes between both.
ASKER
andrew_2706

Apologies everyone as this is all new to me I'm not quite understanding.

As i said at the end of my first message I really wanted them as contacts but didn't think it could be done but I've been playing and managed to get them in as contacts but don't understand this -delimiter to get the other values imported as only the first entry in the CSV is uploaded.

current import string imports them as contacts in the container I want: PS C:\scripts> Import-Csv .\test.csv | New-ADObject -Type contact -Path "ou=sarkcontacts,dc=domain,dc=net"

CSV file:
samaccountname,name,homephone
test company,test company,01702 123456
mark,mark,07889123456
Michelangelo

Import-csv uses comma as delimiter between fields.
your csv file is using comma to separate fields BUT ALSO OrganizationalUnit field uses comma to separate path fields:

givenName,name,telephonenumber,ou
test company,test company,01702 123456,OU=SarkContacts,DC=domain,DC=net

Open in new window


In your last post you pasted a different example: noo OU field therefore no comma inside a field therefore no issue.

You can use a different separator and specify it via -delimiter parameter to import-csv

givenName|name|OfficePhone|organizationalunit
test company|test company|01702 123456|OU=SarkContacts,DC=domain,DC=net

Open in new window


import-csv .\test.csv -delimiter "|" | new-aduser blah

Open in new window

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER
andrew_2706

If I add the -delimiter in the string I get this error:

Import-Csv : A positional parameter cannot be found that accepts argument '.\te
st.csv'.
At line:1 char:11
+ Import-Csv <<<<  .\test.csv -delimiter "|" New-ADObject -Type contact
    + CategoryInfo          : InvalidArgument: (:) [Import-Csv], ParameterBind
   ingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
   .Commands.ImportCsvCommand
Qlemo

The other way is keep the commas, and enclose (at least) the OU in double quotes:
givenName,name,telephonenumber,ou
test company,test company,01702 123456,"OU=SarkContacts,DC=domain,DC=net"

Open in new window

but it is better to use a delimiter you are certain does not appear in your data.
Qlemo

You'Ve missed a pipe operator. It is
Import-Csv .\test.csv -delimiter "|" | New-ADObject -Type contact

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
andrew_2706

PS C:\scripts> Import-Csv .\test.csv -delimiter | New-ADObject -Type contact
Import-Csv : Missing an argument for parameter 'Delimiter'. Specify a parameter
 of type 'System.Char' and try again.
At line:1 char:33
+ Import-Csv .\test.csv -delimiter <<<<  | New-ADObject -Type contact
    + CategoryInfo          : InvalidArgument: (:) [Import-Csv], ParameterBind
   ingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.Im
   portCsvCommand
Qlemo

You still didn't type what we posted. Please check again.
oBdA

For contacts, you don't need (can't use) the SamAccountName.
It works the same way as I used above: you use a loop and you set the properties you want.
You can happily use a regular comma separated csv, provided that fields which include the delimiter are enclosed in double quotes. In fact, all fields should be enclosed in double quotes (Excel does that when you save as csv, so does PowerShell's Export-Csv).
To find the attributes/properties you set, enable "Advanced View" in the ADUC console, then open the properties of a contact. You'll find a tab "Attribute Editor", where you can identify the properties you can set.
The additional properties (the ones that New-ADObject doesn't support directly in the command line) need to be added to the $otherAttributes variable.
"givenName","name","homephone","ou"
"test company","test company","01702 123456","OU=SarkContacts,DC=domain,DC=net"
"marky","mark","07889123456","OU=SarkContacts,DC=domain,DC=net"

Open in new window

Import-Csv .\test.csv | ForEach-Object {
	$contactArgs = @{
		Name =			$_.Name
		DisplayName =	"$($_.Name), $($_.GivenName)"
		Path =			$_.OU
	}
	$otherAttributes = @{
		GivenName =		$_.GivenName
		HomePhone =		$_.homephone
	}
	"User '$($_.Name)'" | Write-Host
	New-ADObject -Type Contact @contactArgs -OtherAttributes $otherAttributes
}

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER
andrew_2706

Qlemo


PS C:\scripts> Import-Csv .\test.csv -delimiter "|" New-ADObject -Type contact
Import-Csv : A positional parameter cannot be found that accepts argument 'New-
ADObject'.
At line:1 char:11
+ Import-Csv <<<<  .\test.csv -delimiter "|" New-ADObject -Type contact
    + CategoryInfo          : InvalidArgument: (:) [Import-Csv], ParameterBind
   ingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
   .Commands.ImportCsvCommand

PS C:\scripts>
ASKER
andrew_2706

oBdA

When I save in Excel as a csv I don't get it in double quotes....
oBdA

Excel will do that for fields that contain the delimiter (or line feeds).
Export-Csv does it for every field.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Michelangelo

Andrew you keep typpng it wrong. Can't ypu paste it?


-delimiter "|" | new-aduser
ASKER
andrew_2706

PS C:\scripts> Import-Csv .\test.csv -delimiter "|" | New-ADObject -Type contact
 -Path "ou=sarkcontacts,dc=domain,dc=net"
New-ADObject : The input object cannot be bound to any parameters for the comma
nd either because the command does not take pipeline input or the input and its
 properties do not match any of the parameters that take pipeline input.
At line:1 char:52
+ Import-Csv .\test.csv -delimiter "|" | New-ADObject <<<<  -Type contact -Path
 "ou=sarkcontacts,dc=domain,dc=net"
    + CategoryInfo          : InvalidArgument: (@{givenName,"na..."01702 12345
   6"}:PSObject) [New-ADObject], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.ActiveDirectory.Ma
   nagement.Commands.NewADObject

New-ADObject : The input object cannot be bound to any parameters for the comma
nd either because the command does not take pipeline input or the input and its
 properties do not match any of the parameters that take pipeline input.
At line:1 char:52
+ Import-Csv .\test.csv -delimiter "|" | New-ADObject <<<<  -Type contact -Path
 "ou=sarkcontacts,dc=dwdsl,dc=net"
    + CategoryInfo          : InvalidArgument: (@{givenName,"na...,"0788912345
   6"}:PSObject) [New-ADObject], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.ActiveDirectory.Ma
   nagement.Commands.NewADObject
oBdA

You can't create a contact with the properties you want by piping a csv to New-ADObject.
There's no way around a loop, as described in https:#a42759618
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
andrew_2706

I give up as I don't understand
oBdA

There's a sample csv and a script in https:#a42759618
What is it you don't understand?
Mahesh

you can hire somebody to work for you and make you understand script and user creation
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
andrew_2706

oBDA

On the assumption I simply copy and paste the script it doesn't work.

PS C:\scripts> Import-Csv .\test.csv | ForEach-Object {
>>     $contactArgs = @{
>>         Name =$_.Name
>>         DisplayName ="$($_.Name), $($_.GivenName)"
>>         Path =$_.OU
>>     }
>>     $otherAttributes = @{
>>         GivenName =$_.GivenName
>>         HomePhone =$_.homephone
>>     }
>>     "User '$($_.Name)'" | Write-Host
>>     New-ADObject -Type Contact @contactArgs -OtherAttributes $otherAttributes

>> }
>>
User 'A C Solutions'
New-ADObject : Cannot bind parameter 'OtherAttributes' to the target. Exception
 setting "OtherAttributes": "Object reference not set to an instance of an obje
ct."
At line:12 char:61
+     New-ADObject -Type Contact @contactArgs -OtherAttributes <<<<  $otherAttr
ibutes
    + CategoryInfo          : WriteError: (:) [New-ADObject], ParameterBinding
   Exception
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.ActiveDirectory
   .Management.Commands.NewADObject

User 'mark'
New-ADObject : Cannot bind parameter 'OtherAttributes' to the target. Exception
 setting "OtherAttributes": "Object reference not set to an instance of an obje
ct."
At line:12 char:61
+     New-ADObject -Type Contact @contactArgs -OtherAttributes <<<<  $otherAttr
ibutes
    + CategoryInfo          : WriteError: (:) [New-ADObject], ParameterBinding
   Exception
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.ActiveDirectory
   .Management.Commands.NewADObject

PS C:\scripts>
oBdA

You save the csv as test.csv, and the script as Import-Contacts.ps1 or whatever.ps1 in the same folder.
You open a PS console, "cd" into the folder where you saved the files, and run .\Import-Contacts.ps1
I just copied both files back from here, adjusted only the target OU, and it worked just as it should.
In $contactArgs, you can specify one or more of the following properties/arguments on the left-hand side of the "=" sign:
Description, DisplayName, Name, Path
On the right-hand side of the "=", you need to specify the respective column name of the csv, or whatever you want to set the property to (like DisplayName, which is built from the Name and GivenName columns).
In $otherAttributes, you can specify other settable properties (see the description in https:#a42759618 on how to find the names) on the left-hand side of the "=" sign.
Right-hand side same as in $contactArgs
ASKER
andrew_2706

As Mahesh said I could pay someone to do this, so have posted on another site for someone to do this as clearly I'm still doing something wrong.


PS C:\Users\Administrator> cd C:\scripts
PS C:\scripts> .\Import.ps1
File C:\scripts\Import.ps1 cannot be loaded because the execution of scripts is
 disabled on this system. Please see "get-help about_signing" for more details.

PS C:\scripts> Set-ExecutionPolicy RemoteSigned



PS C:\scripts> .\Import.ps1
User 'A C Solutions'
New-ADObject : Cannot bind parameter 'OtherAttributes' to the target. Exception
 setting "OtherAttributes": "Object reference not set to an instance of an obje
ct."
At C:\scripts\Import.ps1:12 char:58
+     New-ADObject -Type Contact @contactArgs -OtherAttributes <<<<  $otherAttr
ibutes
    + CategoryInfo          : WriteError: (:) [New-ADObject], ParameterBinding
   Exception
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.ActiveDirectory
   .Management.Commands.NewADObject

User 'mark'
New-ADObject : Cannot bind parameter 'OtherAttributes' to the target. Exception
 setting "OtherAttributes": "Object reference not set to an instance of an obje
ct."
At C:\scripts\Import.ps1:12 char:58
+     New-ADObject -Type Contact @contactArgs -OtherAttributes <<<<  $otherAttr
ibutes
    + CategoryInfo          : WriteError: (:) [New-ADObject], ParameterBinding
   Exception
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.ActiveDirectory
   .Management.Commands.NewADObject

PS C:\scripts>
Your help has saved me hundreds of hours of internet surfing.
fblack61
Michelangelo

Experts-exchange also offers paid help.
https://www.experts-exchange.com/live/
ASKER CERTIFIED SOLUTION
andrew_2706

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question