Import Users into AD With One Line and Two Commands

I think one of the coolest things about PowerShell is pipeline parameter binding. It can't always make things easier, but it OFTEN can. Consider this example of how to read a CSV file and create new users based on the information in that CSV:

Don Jones

July 8, 2010

2 Min Read
ITPro Today logo in a gray background | ITPro Today

I'm in vacation next week, so I'm doubling up on the blogging this week... 


I think one of the coolest things about PowerShell is pipeline parameter binding. It can't always make things easier, but it OFTEN can. Consider this example of how to read a CSV file and create new users based on the information in that CSV:


Start by assuming I have a CSV file whose column headers align to AD attributes:


samaccountname,name,department,title,city,sn

DonJ,DonJ,IT,CTO,Las Vegas,Jones

GregS,GregS,Custodial,Janitor,Denver,Shields


The "poor" way of doing this in PowerShell - a way remarkably similar to VBScript, in fact - would be to load the lines of the CSV into a variable, enumerate them, and then use the information to populate New-ADUser parameters:


$names = Import-CSV names.csv

foreach ($name in $names) {

 new-aduser -name $name.name -samaccountname $name.samaccountname `

  -department $name.department -city $name.city -sn $name.sn

}


You could collapse that into a one-liner, but it's the same basic approach:


import-csv names.csv | foreach-object { new-aduser -name $_.name 

 -samaccountname $_.samaccountname -department $_.department

 -city $_.city -title $_.title }


You don't need to work that hard. All of those New-ADUser parameters support pipeline parameter binding "ByPropertyName." That means if I pipe in an object or objects - like the ones produced by Import-CSV - PowerShell will look for properties on those objects which match the parameter names of the next command. Matching properties are "fed" to their parameters. So this works just as well:


import-csv names.csv | new-aduser


Done. Really, it's that simple. Try it. So long as the CSV column names match the New-ADUser parameter names, you're gold. And if they don't, you can actually use Select-Object in between those two commands to RENAME columns so that they DO match the parameters of New-ADUser!


My PowerShell home page offers access to the latest blog articles, along with PowerShell FAQs - why not bookmark it? You can also get the latest on Windows PowerShell in my Twitter feed @concentrateddon. And, if you’d like to download recent conference materials (slide decks, scripts, etc) I’ve delivered, visit ConcentratedTech.com. That site also contains details on upcoming classes and conferences.


And hey... my ability to keep doing this blog depends on large part upon lots of folks reading it. So tell a colleague, 'kay?

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like