We help IT Professionals succeed at work.

Import Users into AD with Active Directory Module for Windows Powershell

196 Views
Last Modified: 2018-12-21
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
Comment
Watch Question

MaheshArchitect
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
if you could upload csv and script, we can find out the issue

Author

Commented:
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
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
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

MaheshArchitect
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
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"Batchelor", Developer and EE Topic Advisor
CERTIFIED EXPERT
Top Expert 2015

Commented:
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.
MichelangeloSystem Administrator / Postmaster
CERTIFIED EXPERT

Commented:
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.
Qlemo"Batchelor", Developer and EE Topic Advisor
CERTIFIED EXPERT
Top Expert 2015

Commented:
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.

Author

Commented:
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
MichelangeloSystem Administrator / Postmaster
CERTIFIED EXPERT

Commented:
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

Author

Commented:
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"Batchelor", Developer and EE Topic Advisor
CERTIFIED EXPERT
Top Expert 2015

Commented:
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"Batchelor", Developer and EE Topic Advisor
CERTIFIED EXPERT
Top Expert 2015

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

Open in new window

Author

Commented:
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"Batchelor", Developer and EE Topic Advisor
CERTIFIED EXPERT
Top Expert 2015

Commented:
You still didn't type what we posted. Please check again.
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
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

Author

Commented:
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>

Author

Commented:
oBdA

When I save in Excel as a csv I don't get it in double quotes....
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
Excel will do that for fields that contain the delimiter (or line feeds).
Export-Csv does it for every field.
MichelangeloSystem Administrator / Postmaster
CERTIFIED EXPERT

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


-delimiter "|" | new-aduser

Author

Commented:
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
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
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

Author

Commented:
I give up as I don't understand
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
There's a sample csv and a script in https:#a42759618
What is it you don't understand?
MaheshArchitect
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
you can hire somebody to work for you and make you understand script and user creation

Author

Commented:
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>
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
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

Author

Commented:
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>
MichelangeloSystem Administrator / Postmaster
CERTIFIED EXPERT

Commented:
Experts-exchange also offers paid help.
https://www.experts-exchange.com/live/
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.