0
0
PowerShellscripting~5 mins

CSV operations (Import-Csv, Export-Csv) in PowerShell

Choose your learning style9 modes available
Introduction

CSV files store data in a simple table format. Import-Csv and Export-Csv help you read and write these files easily in PowerShell.

You want to read a list of users from a CSV file to process them in a script.
You need to save script results like system info into a CSV file for reports.
You want to convert data from a CSV file into PowerShell objects to filter or sort.
You need to export data from PowerShell into a CSV file to share with others.
You want to automate importing and exporting data between applications using CSV.
Syntax
PowerShell
Import-Csv -Path <filepath>
Export-Csv -Path <filepath> [-NoTypeInformation]

Import-Csv reads a CSV file and creates objects with properties from the columns.

Export-Csv converts objects into CSV format and saves to a file. Use -NoTypeInformation to skip extra type info line.

Examples
Reads the file users.csv and creates objects for each row.
PowerShell
Import-Csv -Path "users.csv"
Saves the objects in $data to output.csv without extra type info.
PowerShell
$data | Export-Csv -Path "output.csv" -NoTypeInformation
Reads data.csv and filters rows where Age is greater than 30.
PowerShell
Import-Csv -Path "data.csv" | Where-Object { [int]$_.Age -gt 30 }
Sample Program

This script reads a CSV file with user data, filters users older than 25, saves the filtered list to a new CSV file, and prints their details.

PowerShell
## Sample CSV content saved as users.csv:
# Name,Age,City
# Alice,28,New York
# Bob,35,Chicago
# Carol,22,Seattle

# Import CSV file
$users = Import-Csv -Path "users.csv"

# Filter users older than 25
$olderUsers = $users | Where-Object { [int]$_.Age -gt 25 }

# Export filtered users to new CSV
$olderUsers | Export-Csv -Path "older_users.csv" -NoTypeInformation

# Display filtered users
$olderUsers | ForEach-Object { "Name: $($_.Name), Age: $($_.Age), City: $($_.City)" }
OutputSuccess
Important Notes

CSV files must have a header row with column names for Import-Csv to work properly.

Export-Csv adds a type information line by default; use -NoTypeInformation to avoid this.

Imported CSV data is treated as strings; convert types if needed (e.g., [int]$_.Age).

Summary

Use Import-Csv to read CSV files into objects you can work with in PowerShell.

Use Export-Csv to save objects back into CSV files for sharing or reports.

Filtering and processing CSV data is easy by combining these commands with PowerShell pipelines.