Skip to main content

PowerShell Import-CSV: Complete Guide with ForEach, Filtering & Examples [2024]

3 min read
powershell import-csv foreach loop csv data processing file operations

Master PowerShell Import-CSV—the essential cmdlet for reading CSV files. This comprehensive guide covers basic imports, custom headers, filtering, pipeline processing, and production patterns.

Quick Syntax

Import-Csv -Path "C:\data.csv" | ForEach-Object { $_.<PropertyName> }

Import-CSV Basics

Simple CSV Import

# Basic import
$data = Import-Csv -Path "C:\users.csv"
$data | Select-Object -First 3

ForEach Loop Processing

$csvFile = "C:\data.csv"
$data = Import-Csv -Path $csvFile

foreach ($row in $data) {
    Write-Output "Name: $($row.Name), Age: $($row.Age)"
}

Property Access

Accessing CSV Columns

# Headers become properties
$row.Name          # Access Name column
$row."First Name"  # Columns with spaces need quotes
$row[$($row | Get-Member -MemberType NoteProperty | Select-Object -First 1 | Select-Object -ExpandProperty Name)]

Custom Headers

Specify Header Names

$data = Import-Csv -Path "data.csv" -Header "ID", "Name", "Email"

No Header in CSV

$data = Import-Csv -Path "data.csv" -Header "Col1", "Col2", "Col3" -Delimiter ","

Delimiter Options

Different Delimiters

# Tab-delimited
Import-Csv -Path "data.tsv" -Delimiter "`t"

# Semicolon
Import-Csv -Path "data.csv" -Delimiter ";"

# Pipe
Import-Csv -Path "data.txt" -Delimiter "|"

Filtering Data

Filter After Import

$data = Import-Csv -Path "users.csv"
$filtered = $data | Where-Object { $_.Age -gt 25 }

Filter Before Processing

Import-Csv -Path "orders.csv" |
    Where-Object { [double]$_.Amount -gt 100 } |
    ForEach-Object { "Order $($_.OrderID): $($_.Amount)" }

Pipeline Processing

Direct Pipeline

Import-Csv -Path "data.csv" |
    Select-Object Name, Department |
    Export-Csv -Path "output.csv" -NoTypeInformation

Transform Data

Import-Csv -Path "prices.csv" |
    ForEach-Object {
        $_ | Add-Member -NotePropertyName "Total" -NotePropertyValue ([double]$_.Price * [double]$_.Quantity)
        $_
    } |
    Export-Csv -Path "totals.csv" -NoTypeInformation

Error Handling

Handle Missing Files

if (Test-Path -Path "C:\data.csv") {
    $data = Import-Csv -Path "C:\data.csv"
} else {
    Write-Error "CSV file not found"
}

Validate Data

$data = Import-Csv -Path "data.csv"

foreach ($row in $data) {
    if ([string]::IsNullOrWhiteSpace($row.Name)) {
        Write-Warning "Row has empty Name: $($row | Out-String)"
    }
}

Large File Handling

Process Large CSVs Efficiently

# Read line by line
$reader = [System.IO.File]::OpenText("huge.csv")
$header = $reader.ReadLine() -split ","

while ($reader.Peek() -ge 0) {
    $line = $reader.ReadLine() -split ","
    $row = @{}
    for ($i = 0; $i -lt $header.Count; $i++) {
        $row[$header[$i]] = $line[$i]
    }
    # Process $row
}
$reader.Close()

Type Conversion

Convert String to Numbers

Import-Csv -Path "data.csv" |
    ForEach-Object {
        $_.Age = [int]$_.Age
        $_.Salary = [double]$_.Salary
        $_
    }

Real-World Examples

Process User List

$users = Import-Csv -Path "C:\users.csv"

foreach ($user in $users) {
    New-ADUser -Name $user.Name -SamAccountName $user.Username -Path $user.OUPath
}

Export Report

Import-Csv -Path "sales.csv" |
    Where-Object { [double]$_.Amount -gt 1000 } |
    Group-Object -Property Region |
    ForEach-Object { [PSCustomObject]@{Region=$_.Name; Total=($_.Group.Amount | Measure-Object -Sum | Select-Object -ExpandProperty Sum)} } |
    Export-Csv -Path "report.csv" -NoTypeInformation

Best Practices

✅ Always validate file exists ✅ Handle encoding issues (UTF-8 default) ✅ Specify delimiter explicitly ✅ Convert data types as needed ✅ Use error handling ✅ Test with sample files first


Troubleshooting

Issue: “Property not found”

  • Cause: Column name doesn’t match
  • Solution: Use Get-Member to check property names

Issue: “Cannot convert value”

  • Cause: Type mismatch
  • Solution: Explicitly cast with [type]

CSV Operations

  • PowerShell Export-CSV - Export to CSV files
  • ConvertTo-CSV - Convert to CSV format
  • ConvertFrom-CSV - Convert from CSV format
  • Get-Content - Read raw CSV content

Data Processing & Iteration

Data Structures

Control Flow & Logic

Data Type Handling

Active Directory Integration

File Operations

Sorting & Output

Functions & Organization

  • PowerShell Functions - Create reusable import functions
  • PowerShell Complete Guide - Full reference

Comprehensive Guides