How to create an array in PowerShell from CSV file

In this PowerShell tutorial, we will discuss how to create a PowerShell array from a CSV file. We can easily create an array from a comma-separated string in PowerShell. PowerShell create array from csv file example in detail.

PowerShell create array from CSV file

To create an array from a CSV file in PowerShell, we need to first create the CSV file.

I have created a CSV file with below two columns:

  • Name
  • Salary

The CSV file looks like below:

powershell array from csv

We can use Import-Csv to manipulate and work with a CSV file.

The Import-CSV cmdlets in PowerShell create a table like custom objects from the items presented in the CSV file.

In the below PowerShell script, we will use the Import-CSV cmdlets to assign the CSV file data to a variable of PowerShell array type.

You can run the below script in PowerShell ISE.

$users=Import-Csv E:\Bijay\Users.csv
$users

You can see the output in the array format.

powershell array from csv file

Access Array Elements after import-csv

We can access various array elements after creating an array using Import-Csv.

To access all the elements, we can use the object like below:

$users=Import-Csv E:\Bijay\Users.csv
$users

To retrieve the first element from the array we can write the PowerShell cmdlet like below:

$users=Import-Csv E:\Bijay\Users.csv
$users[0]
powershell create array import-csv

We can access the property from a particular element from the PowerShell array like below:

$users=Import-Csv E:\Bijay\Users.csv
$users[0].Name
powershell create array from comma separated string

We can count the number of elements by using the count property like below:

$users=Import-Csv E:\Bijay\Users.csv
$users.Count
powershell create array from csv

Import into different arrays in PowerShell

We can also import into different arrays based on the column after creating an array from the csv file in PowerShell.

We can use Import-CSV foreach to loop through PowerShell array.

Here, I have created two empty array and then I am assigning the values to it.

$Names=@()
$Salaries =@()
Import-Csv E:\Bijay\Users.csv | ForEach-Object {
    $Names += $_.Name
    $Salaries += $_.Salary
}
$Names
Write-Host("******************")
$Salaries

$_ represents the current object or the current row.

You can see the output like below:

powershell create array from csv file

Here, the first array displays the Names, and the second array displays the Salaries.

You may like following tutorials:

In this tutorial we learned:

  • How to create an array from CSV file
  • Access Array Elements after import-csv
  • Import into different arrays in PowerShell
  • Hello, Bijay.
    Would you please help provide a sample powershell script “how to create Hashtable from CSV file”. Looking forward to hearing from you. Thanks.
    PS I have learned a lot from your blog “how to create an array from CSV file”.

  • >