0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Extract Column from CSV File

Use Import-Csv 'file.csv' | Select-Object -ExpandProperty ColumnName to extract a column from a CSV file in PowerShell.
📋

Examples

InputCSV file with columns Name, Age; extract Name
OutputAlice Bob Charlie
InputCSV file with columns Product, Price; extract Price
Output10.99 5.49 20.00
InputCSV file with columns City, Country; extract Country
OutputUSA Canada Mexico
🧠

How to Think About It

To extract a column from a CSV file, first read the file as objects using Import-Csv. Then select the desired column by its header name using Select-Object -ExpandProperty to get just the values of that column.
📐

Algorithm

1
Read the CSV file into a list of objects.
2
Select the property (column) you want from each object.
3
Output the values of that column.
💻

Code

powershell
Import-Csv 'data.csv' | Select-Object -ExpandProperty Name
Output
Alice Bob Charlie
🔍

Dry Run

Let's trace extracting the 'Name' column from a CSV with three rows.

1

Import CSV

Reads data.csv into objects: [{Name: 'Alice', Age: '30'}, {Name: 'Bob', Age: '25'}, {Name: 'Charlie', Age: '35'}]

2

Select Column

Extracts the 'Name' property from each object: ['Alice', 'Bob', 'Charlie']

Name
Alice
Bob
Charlie
💡

Why This Works

Step 1: Import-Csv reads the file

Import-Csv converts each row of the CSV into an object with properties named after the headers.

Step 2: Select-Object extracts the column

Select-Object -ExpandProperty ColumnName pulls out just the values of the specified column from each object.

🔄

Alternative Approaches

Using ForEach-Object
powershell
Import-Csv 'data.csv' | ForEach-Object { $_.Name }
This method also extracts the column but uses a loop instead of Select-Object; slightly more flexible for adding processing.
Using ConvertFrom-Csv with Get-Content
powershell
Get-Content 'data.csv' | ConvertFrom-Csv | Select-Object -ExpandProperty Name
Reads the file line by line then converts to CSV objects; useful if you want to process the file as text first.

Complexity: O(n) time, O(n) space

Time Complexity

The script reads each row once, so time grows linearly with the number of rows.

Space Complexity

Memory usage grows linearly with the number of rows because all rows are loaded into objects.

Which Approach is Fastest?

Using Select-Object -ExpandProperty is efficient and concise; ForEach-Object adds slight overhead but allows more processing.

ApproachTimeSpaceBest For
Select-Object -ExpandPropertyO(n)O(n)Simple column extraction
ForEach-Object loopO(n)O(n)Adding custom processing per row
ConvertFrom-Csv with Get-ContentO(n)O(n)Processing file as text before CSV parsing
💡
Use -ExpandProperty to get plain values instead of objects when extracting a column.
⚠️
Forgetting to use -ExpandProperty results in output objects instead of just the column values.