PowerShell: How to Use Import-Csv and Foreach


Often you may want to use the Import-Csv cmdlet in PowerShell along with a Foreach-Object statement to loop through each line in a CSV file and perform some action.

You can use the following basic syntax to do so:

Import-CSV $my_file | Foreach-Object{
    Write-Host $_.my_column
}

This particular example will loop through each line in the CSV file located at the path stored in the $my_file variable and output the value from the column in the fie named my_column.

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

Example: How to Use Import-Csv and ForEach in PowerShell

Suppose we have a CSV file saved in the following location:

  • c:\users\bobbi\nba_data.csv

We can use the Get-Content cmdlet to view the contents of this file:

We can see that this CSV file contains three columns with information about various basketball teams.

Suppose that we would like to loop through each row in the file and output the following:

  • Team – Assists

We can use the following syntax to do so:

Import-CSV $my_file | Foreach-Object{
    Write-Host $_.team "-" $_assists
}

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

PowerShell Import-Csv Foreach

Notice that we’re able to loop through each row in the CSV file and output the name of the team followed by a dash followed by the number of assists.

Note that this is simply one example of how to use Import-Csv along with the Foreach-Object statement.

You can use similar syntax to perform a specific action on each line in a CSV file.

Simply replace the line inside the Foreach-Object loop with whatever action you would like to perform.

Related Tutorials

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

PowerShell: How to List Files in Directory by Date
PowerShell: How to Get Most Recently Modified File in Directory
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply