31 July,2012 by Tom Collins
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 }
This is only a preview. Your comment has not yet been posted.
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.
Posted by: |