Q. How can I use Windows PowerShell to read and use a comma-separated value (CSV) file?

John Savill

April 13, 2008

1 Min Read
ITPro Today logo

A. The PowerShell cmdlet Import-csv lets you read and manipulate a CSV file. The following code and output is an example of the command you would use to view a CSV file. Take note that the CSV's first row defines each column.

D:DocumentsBooksComplete Windows LonghornImages> import-csv "Chapter 3 Image Names.csv"

The return would be:

Old Name new name
-------- --------
3-inst1.tif 03wls01.tif
3-inst2.tif 03wls02.tif
3-inst3.tif 03wls03.tif
3-inst4.tif 03wls04.tif

The cmdlet’s real strength is manipulating the output. For example, while writing The Complete Guide to Windows Server 2008, I used my own image-naming format, which wasn't the correct format for the final production manuscript. So I used a CSV file to rename the documents, mapping the old name to its true standards-based name.

To access each CSV-file row of data, you must acquire each as an object. Then, examine the values named by each column by using code similar to the following:

PS D:DocumentsBooksComplete Windows LonghornImages> import-csv "Chapter 3 Image Names.csv" | foreach-object {write-host $_."old name" $_."new name"}

The return would be:

3-inst1.tif 03wls01.tif
3-inst2.tif 03wls02.tif
3-inst3.tif 03wls03.tif
3-inst4.tif 03wls04.tif

You'll notice that I placed column names only in quotes because I have a space in the column names. I can rename a column by changing write-host to rename-item, similar to the following sample code, and I'm done:

PS D:DocumentsBooksComplete Windows LonghornImages> import-csv "Chapter 4 Image Names.csv" | foreach-object {rename-item $_."old name" $_."new name"}

About the Author(s)

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like