June 12, 2009

Working with CSV Files


Working with CSV file content in Powershell is a perfect match, and very easy and efficient. Reading data from a csv file for use in Powershell is done using the Import-CSV cmdlet. The data is read from the file and stored in an object that you define.

Consider the following users.csv file content:



FNameLNamesamAccountNamePrimarySMTPAddress
JohnSmithsmithjsmithj@contoso.com
MaryJonesjonesmjonesm@contoso.com


To import the data from the users.csv file into an object called NewUsers, use the following Powershell cmdlet syntax...
$NewUsers = Import-CSV users.csv

After the import, you will have an object called $NewUsers to work with in Powershell. You can display the entire contents by typing the variable name $NewUsers.

You can process the entries individually by using the ForEach statement shown below:
ForEach ($User in $NewUsers) {write-host Email $User.Fname $User.LName at $User.PrimarySMTPAddress}

Output from the statement above would produce:
Email John Smith at smithj@contoso.com
Email Mary Jones at jonesm@contoso.com

Although this is a very simple example, it shows how easy it is to work with csv file data in Powershell. We make extensive use of csv files in our Exchange hosting environment for creating new mailboxes for our campus customers as well as modifying existing users, distribution groups, forwarding addresses, quota, etc. It works well for use and has made day-to-day mudane tasks much easier to process.

...more to come in our Bulk User & Mailbox Management post.

No comments:

Post a Comment