PowerShell: How to Loop Through Each Line of CSV File


You can use the following syntax in PowerShell to loop through each line of a CSV file:

$my_csv = Import-Csv "basketball_data.csv"

foreach ($row in $my_csv) {
    "points: $($row.points)"
}

This particular example imports the CSV file named basketball_data.csv, then loops through each row of the file and prints the value from the points column.

The following example shows how to use this syntax in practice.

Example: How to Loop Through Each Line of CSV File in PowerShell

Suppose that we have a file named basketball_data.csv stored in our current directory.

We can use the following syntax to view the contents of this CSV file:

$my_csv = Import-Csv "basketball_data.csv"

$my_csv

The following screenshot shows how to use this syntax in practice:

Suppose that we would like to loop through each row of this CSV file and print the value from the points column only.

We can use the following syntax to do so:

$my_csv = Import-Csv "basketball_data.csv"

foreach ($row in $my_csv) {
    "points: $($row.points)"
}

The following screenshot shows how to use this syntax in practice:

Notice that this loops through each row of the CSV file and prints the text “points:” followed by the value in the points column.

Note that you can use similar syntax to print the values from several columns in each row.

For example, we can use the following syntax to loop through each row and print the values from both the team and points columns:

$my_csv = Import-Csv "basketball_data.csv"

foreach ($row in $my_csv) {
    "team: $($row.team), points: $($row.points)"
}

The following screenshot shows how to use this syntax in practice:

PowerShell loop through CSV and print values from specific columns

This syntax loops through each row of the CSV file and prints the values from the team and points columns.

Feel free to use similar syntax to loop through the rows of your own CSV file and perform whatever operations you’d like.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Rename File Extension of Multiple Files
PowerShell: How to Replace Every Occurrence of String in File

Leave a Reply