PowerShell: Bulk administration using CSV imports

By | 2017-01-24T09:53:53+00:00 April 7th, 2014|IT Services|

In today’s post I am going to discuss a very flexible yet simple technique I use to accomplish bulk administration tasks in PowerShell using the import-csv and the ForEach-Object cmdlets.  In today’s example we will be looking at bulk imports of Mail Contacts (New-MailContact) in Exchange.  The task itself could be anything however the concept here remains the same.

The first thing we need to determine is which parameters are required for the New-MailContact cmdlet.  To do this use Get-Help New-MailContact.  From the results we see that -ExternalEmailAddress and -Name are required parameters.  At a minimum our csv needs to include data for these two fields.


Next build the CSV.  I typically name the headers to match the parameter names I plan to use during the import.  This simplifies the syntax later however matching the header names to the parameter names is not a requirement.


In this example Ill save the file as c:\users.csv.  If creating the CSV in Excel be sure to change Save as type to CSV (Comma delimited).


Next, verify your CSV imports successfully by running import-csv c:\users.csv. If any errors are found in your csv, resolve them before moving forward.


Next pipe the results of import-csv to ForEach-Object and specify the action to take for each object within {}.  In this case, import-csv C:\users.csv | ForEach-Object {New-MailContact}. Now, at a minimum, add the required parameters as part of New-MailContact and specify the values found in the CSV by using $_. followed by the the column header name (-Name $_.FirstName).  The final syntax should look something like this.

import-csv “C:\users.csv” | ForEach-Object {New-MailContact -name $_.FirstName –FirstName $_.FirstName –LastName $_.LastName -ExternalEmailAddress $_.ExternalAddress -OrganizationalUnit $_.OrganizationalUnit -Displayname $_.FirstName}


That is it!  A very simple yet versatile way to complete bulk administration tasks in almost any environment using Import-CSV coupled with ForEach-Object.

About the Author:

Mike Ratcliffe
Mike Ratcliffe is a hard working, self motivated system administrator who adapts quickly to new technology, concepts and environments. With over a decade of experience in information technology and having held numerous titles and responsibilities throughout his career, he currently focuses on system administration of Microsoft Active Directory and related technologies, Microsoft Exchange as well as VMware virtualization.