How to Extract a Column From a CSV File and Store It in a Variable in PowerShell

John Wachira Feb 02, 2024
How to Extract a Column From a CSV File and Store It in a Variable in PowerShell

This article illustrates how we can extract a specific column from a CSV file and save it in a variable on PowerShell. We use the Import-Csv cmdlet to make a table of custom objects from a comma-separated value file.

Extract a Column From a CSV File and Store It in a Variable Using the PowerShell Import-Csv Cmdlet

We can use the PowerShell Import-Csv cmdlet to create a table from a comma-separated value file. The columns of a CSV file become the property, while the rows become the property values.

The Import-Csv cmdlet is compatible with all CSV files, including files made with the Export-Csv cmdlet. Let’s look at an example.

The command below will attempt to create a table from the custom objects of our Trial.csv file using the Import-Csv cmdlet.

Import-Csv -Path ./Trial.csv

This will import our Trail.csv file in the format shown below.

PowerShell Import-Csv

We can format the output into a table with the Format-Table switch as illustrated below:

Import-Csv -Path ./Trial.csv | Format-Table

Here is the formatted table:

PowerShell Format-Table

Now that we have familiarized ourselves with the Import-Csv cmdlet let’s discuss how we can extract a specific column from the table above and store it in a variable. Assuming we want to get the values in the Username column and store the values in a variable, how do we go about it?

In the command below, we will attempt to save the Username column in the $user variable.

$user = Import-Csv .\Trial.csv | select -ExpandProperty Username

This will store the values of the Username column in the $user variable. We can take a quick peek at the content of our $user variable.

user variable

We can use the Import-Csv cmdlet to create a table of custom objects from a comma-separated value file. Adding the select -ExpandProperty parameter will allow you to extract a specific column from the cmdlet results.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - PowerShell CSV