DiscoPosse – Using the chicken to measure IT
Technology, Cycling, Music and Madness


Technology

January 23, 2012

CSV, yeah you know me! – PowerShell and the Import-Csv CmdLet – Part 2

More articles by »
Written by: Eric
Tags: , , , , , ,

In part 1 of this series we touched on the basics of using the Import-Csv CmdLet by reading a file into an array variable and extracting elements and data from our input data.

To enhance this process we can now take the data in memory and using a ForEach CmdLet to parse the data and do a multitude of actions with it.

One thing that you may have noticed in the first part of the script is that we named the variable using the pluralized $userobjects rather than the singular $userobject. Why is that you ask? Great question!

To simplify the identification of objects in our array we want to refer to them in a logical way of a singular userobject in an array, or list, of userobjects. While PowerShell doesnt formally use pluralization, I just find it easier to follow and hopefully it’s a better practice of programming.

First we will add the very basic ForEach to output the Usernames to the screen. Using our pluralization format this is what we do:

ForEach ( $userobject in $userobjects ) {
Write-Host Username is $userobject.Username
}

Remember that everything within the curly braces will be performed against each object in the array sequentially and then move on to the next until it reaches the end of the array and moves to the next command outside of the curly braces.

In other words the ForEach loops through the data and then move onwards, so if we want to display all of the usernames, and emails followed by a count of the total records it would look like this:

ForEach ( $userobject in $userobjects ) {
Write-Host Username is $userobject.Username had email $userobject.email
}
Write-Host Total Records = $userobjects.count

Because we are capturing elements and the contained data, it is better to assign these as variables within our loop so that we can address them and also perform other tasks such as concatenation, splitting, calculation and any of a variety of other actions. I prefer to assign a meaningful name in a format like $FileVariableName or $InputVariableName. Here is what I would do in this particular case:

ForEach ( $userobject in $userobjects ) {
#Assign the content to variables
$FileUsername = $userobject.username
$FileFullName = $userobject.”full name”
$FileEmail = $userobject.email
$FileAddress = $userobject.address
$FilePostalCode = $userobject.postalcode
$FilePhoneNumber = $userobject.phone

# Output the content to the screen
Write-Host $FileFullName has a username of $FileUsername with email $FileEmail
}
Write-Host Total Records = $userobjects.count

Notice that because one of our columns had a space in the name (Full Name) we had to enclose the column header name in double quotes as $userobject.”full name” or else it would throw an error.

At this point you can see the capabilities of using your ForEach loop process. Recall that you can also pass along multiple commands to the loop. As long as you have the correct modules loaded, you can now use this process to run Microsoft Exchange  CmdLets such as Get-Contact to check our Exchange directory if these are existing contacts:

ForEach ( $userobject in $userobjects ) {
#Assign the content to variables
$FileUsername = $userobject.username
$FileFullName = $userobject.”full name”
$FileEmail = $userobject.email
$FileAddress = $userobject.address
$FilePostalCode = $userobject.postalcode
$FilePhoneNumber = $userobject.phone

# Output the content to the screen
Write-Host $FileFullName has a username of $FileUsername with email $FileEmail

if ( Get-Contact -Identity $FileEmail ) {
Write-Host $FileFullName exists in the Exchange directory
}
}
Write-Host Total Records = $userobjects.count

Now we’ve expanded our script to make it more reliable, and depending on the complexity of the data we could see many other operations that we require to make use of the input data. The next article in the series will have us attack some additional tasks including:

  • Adding a Header row where one does not exist
  • Expand our Get-Contact query to perform a New-MailContact command if the record does not exist

I hope that you find this helpful. The goal is to lay out the fundamentals that I’ve used for some of the more complex scripts that have been created for tasks such as importing and managing Exchange Contacts, managing Active Directory user account information and many such tasks.



About the Author

Eric





 
 

 
vexpert_logo_q109

vExpert 2013 – Look who just joined the club!!

I have one word to describe the feeling right now: Wow! I am humbled and thankful to VMware, John Troyer, Angelo Luciani and the whole community who have kindly added me to the vExpert list for 2013. This is truly an honour for...
by Eric
0

 
 
tovmug

Toronto VMUG: May 23rd, 2013 Event Recap and Private Cloud Presentation

It was a beautiful sunny morning in Toronto and a great day for a VMUG meeting! May 23rd brought the first VMUG meeting of the spring here and the audience showed that they were ready to show some community love today. There we...
by Eric
0

 
 
newfeature

VMware Hybrid Cloud Launch Day – Why this is important, and What is New

So today is a big announcement day for VMware. Not a total surprise of course, because they have teased this offering for a while, and they have actually had the system in customer beta testing for a while. I know, because I wa...
by Eric
0

 




Join Zipcar and get $50 in free driving Join Zipcar and get $50 in free driving Join Zipcar and get $50 in free driving

6 Comments


  1. [...] part 2 we will expand our script to loop through the elements and show you different ways that we can [...]


  2. Mark

    Hi Eric. Being new to Powershell, I found this VERY helpful. I’m looking for part 3, especially the part about managing AD user account info. Does it exist?


  3. Hi Mark,

    Thanks for the comment and I’m glad you liked it. Strangely enough I had this as an unfinished series. I’ll get it cooked up and posted shortly. Thanks for the reminder :)

    Eric


  4. James

    Eric, I am also new to Powershell (actually new to all types of scripting). Part 1 and Part 2 helped me create my first Powershell script to add acl rights for a group to 5 folders at about 60 different shares. Saved me having to click on then change acl rights on about 300 folders all through our DFS structure!

    I look forward to Part 3 as well.

    Thank you so much!
    James.


  5. Awesome! Thanks for the comment and I’m glad that it has helped :)


  6. Dan

    Great info, good examples. Thank you, and hope you do a part 3. Using this info to create user accounts in bulk, based on an exported CSV from HR.



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>