PowerShell: How to Create Array from CSV File


You can use the following syntax in PowerShell to create an array from a CSV file:

$my_csv = Import-Csv "c:\users\bobbi\basketball_data.csv"

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

This particular example reads in the CSV named basketball_data.csv and creates an array named $my_array that contains only the values from the points column in the CSV file.

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

Example: How to Create an Array from CSV File in PowerShell

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

  • c:\users\bobbi\basketball_data.csv

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

$my_csv = Import-Csv "c:\users\bobbi\basketball_data.csv"

$my_csv

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

We can use the following syntax to read the points column of this CSV file into an array:

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

$my_array

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

PowerShell create array from CSV file

We can see that the array contains all of the values from the points column of the CSV file.

If we’d like, we can also use the following syntax to read the values from each column of the CSV file into an array:

$my_array = foreach ($row in $my_csv) {
    "points: $($row.points), assists: $($row.assists), rebounds: $($row.rebounds)"
}

$my_array

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

We can see that the array now contains all of the values from each of the columns of the CSV file.

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