Loop Through a CSV File Using Foreach in Powershell

CSV is a file of Character-Separated values where a comma is used in most cases as a delimiter. This article discusses two ways of looping through the values of a given CSV file. 

We will be using the baby_names.csv file in our examples. The file has the following contents:

Id,Name,Year,Gender,State,Count
11350,Emma,2004,F,AK,62
11351,Madison, ,F,AK,48
11352,Hannah,2004,F,AK,46
11353, Grace,2004,F,AK,44
11354,Emily,2004,F, ,41
11355,Abigail,2004,F,AK,37
11356,Olivia,2004,F,AK,33

The CSV file is comma-separated with six columns and seven rows. The values on the first row are the headers.

Note: All the commands in this article will be executed on a PowerShell script (.ps1 file). However, you are free to run the code directly from PowerShell.

To execute a PowerShell script, add the code into the .ps1 script, then run the following commands on the PowerShell:

The first command changes the working directory to the folder containing the script, and the second executes the actual script.

Method 1: Using Import-Csv cmdlet and ForEach

The Import-Csv creates table-like objects from the items in a CSV file then we loop through these items.

Script: loop_csv1.ps1

Alternatively, we can loop through the CSV file with items as key-value pairs where the column name is the key.

Script: loop_csv1.ps1

Finding a CSV record based on Column Value

In this subsection, we want to find records based on a given column’s value. This requires us to use an if-statement to check the condition(s).

For example, the script below searches for a baby record based on ID.

Script: loop_while_searching.ps1

Method 2: Using Get-Content and a Loop

The Get-Content cmdlet is used to get the item’s content at the specified location. In our example, we will use it to read the contents of the CSV and then loop through the results.

Script: loop_get_content.ps1

You can then process each row at a time. In the following code, we split the contents of each line along the comma symbol to get the PowerShell list for each row.

Script: loop_get_content2.ps1

Conclusion

This article discussed two methods of looping through a CSV file row by row. The first method discussed using the Import-Csv cmdlet to read CSV content and then loop through it. The second method works similarly but uses Get-Content to read the file.