Use Powershell import-csv to enumerate list items from a CSV array

31 July,2012 by Jack Vamvas

Question: I have a csv file with two columns. Both columns have headers , with values under both columns , with a comma delimiter. An example of the list is :

Musician,Instrument

Prince,Guitar

Hendrix,Guitar

Mozart,Piano

Using Powershell, how can I   import the csv file, enumerate through the list and perform various tasks on the values.

Answer:  Use the import-csv cmdlet and the foreach to import and enumerate the list. I find this process useful in importing a list of dynamically changing servers – such as a SQL Server Inventory.  A server administrator can update the list regularly , where I can execute various reports.

Using the formatted example from above , place the list into a txt file . The code example, presents three basic examples. The first prints out all instances of the array. The second uses the foreach to print out all line, and the third prints out the content of just one column.

 

$csvlist = Import-CSV -Path C:\projects\testing\powershell\csv.txt
#-Delimiter ','
#print all instances in the the array 
$csvlist

#print out all lines
foreach ($item in $csvlist ){
     $item
}

#print out just 1 column
foreach ($item in $csvlist ){
     $item.Musician
}

Author: Jack Vamvas (http://www.sqlserver-dba.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on Use Powershell import-csv to enumerate list items from a CSV array


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer