Home » How to Import CSV into an Array in PowerShell

How to Import CSV into an Array in PowerShell

To import a CSV file into an array using PowerShell, you can use the Import-CSV cmdlet. This command reads the CSV file and creates an array of objects, where each object represents a row in the CSV file and the properties of the object represent the columns in the CSV file.

The following method shows how you can do it with syntax.

Method 1: Import CSV to an array

$processList = Import-CSV -Path $csvFilePath

This example will import the csv file and store its content into an array.

The following example shows how you can use this method.

How to Import CSV to an Array in PowerShell

The following PowerShell script shows how you can use the Import-CSV to import a CSV file and save its content into an array.

# import csv file
$processList = Import-Csv -Path "C:\temp\log\processList.csv"

# print the array content
$processList

# check the type of a variable
$processList.GetType()

Output:

PowerShell import csv file into array
PowerShell import csv file into array

In this script, we use the Import-CSV cmdlet to import a csv file from the specified file path and store its content in the $processList variable.

We then print the array content and check the data type of the variable $processList which is System.Array

You can access the individual rows using their index and you can access the values of specific columns within a row using the column names from the CSV file.

# get the first element
$firstItem = $processList[0]

# Access the values of a specific column in the first row
$firstItem.Name

Output:

PS C:\> $firstItem = $processList[0]
PS C:\> $firstItem

Name            Id
----            --
acumbrellaagent 8380


PS C:\> $firstItem.Name
acumbrellaagent
PS C:\>

Conclusion

I hope the above article on importing a CSV file into an array in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.