Import CSV Files Into Array in PowerShell

  1. the Comma-Separated Values File
  2. Use Import-CSV Cmdlet to Import CSV Files Into Array in PowerShell
  3. Access Elements After Importing CSV Files Into Array in PowerShell
Import CSV Files Into Array in PowerShell

We are often presented with data from different sources in various formats. Usually, the standard format used for data extracts is the CSV format.

This article will discuss reading comma-separated files or CSV data and placing it into an array variable using PowerShell.

the Comma-Separated Values File

A CSV (Comma-Separated Values) file contains data or set separated by commas. This allows the data to be saved in a tabular format.

Users can utilize CSV files with most spreadsheet programs, such as Microsoft Excel or Google Spreadsheets. However, when we open it in software that doesn’t cater to tabular formats, the data will be comma-separated, which PowerShell can use to separate values into arrays.

For example, below is a raw CSV format with two columns.

users.csv file:

Name,Salary
John,1000
Paul,2000
Mary,1500
Matt,3000

Use Import-CSV Cmdlet to Import CSV Files Into Array in PowerShell

The Import-CSV command in Windows PowerShell creates a table like custom objects from the items presented in the CSV file above.

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

$users = Import-CSV C:\PS\users.csv
$users

Once executed, we can see the CSV file values turned to a format list called an ArrayList object.

Output:

Name Salary
---- ------
John 1000
Paul 2000
Mary 1500
Matt 3000

Access Elements After Importing CSV Files Into Array in PowerShell

After creating an array using the Import-CSV cmdlet, we can access several array elements.

To access all elements within the array, we can use the object like our previous example.

$users = Import-CSV C:\PS\users.csv
$users

Output:

Name Salary
---- ------
John 1000
Paul 2000
Mary 1500
Matt 3000

To query for an element from the array, we can append an index indicator to the variable. The example below queries the first data in the array using the index 0 indicators.

$users = Import-CSV C:\PS\users.csv
$users[0]

Output:

Name Salary
---- ------
John 1000

We can query for the property from a particular element from the Windows PowerShell array by treating the column name as a property name like the example below.

$users = Import-CSV C:\PS\users.csv
$users[0].Name

Output:

John

We can count the number of elements in an array using the count property below.

$users = Import-CSV C:\PS\users.csv
$users.Count

Output:

4
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

Related Article - PowerShell Array

Related Article - PowerShell CSV