PowerShell Script to Extract Column from CSV File
Import-Csv 'file.csv' | Select-Object -ExpandProperty ColumnName to extract a column from a CSV file in PowerShell.Examples
How to Think About It
Import-Csv. Then select the desired column by its header name using Select-Object -ExpandProperty to get just the values of that column.Algorithm
Code
Import-Csv 'data.csv' | Select-Object -ExpandProperty NameDry Run
Let's trace extracting the 'Name' column from a CSV with three rows.
Import CSV
Reads data.csv into objects: [{Name: 'Alice', Age: '30'}, {Name: 'Bob', Age: '25'}, {Name: 'Charlie', Age: '35'}]
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
Import-Csv 'data.csv' | ForEach-Object { $_.Name }Get-Content 'data.csv' | ConvertFrom-Csv | Select-Object -ExpandProperty NameComplexity: 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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Select-Object -ExpandProperty | O(n) | O(n) | Simple column extraction |
| ForEach-Object loop | O(n) | O(n) | Adding custom processing per row |
| ConvertFrom-Csv with Get-Content | O(n) | O(n) | Processing file as text before CSV parsing |
-ExpandProperty to get plain values instead of objects when extracting a column.-ExpandProperty results in output objects instead of just the column values.