ConvertFrom-Csv

Understanding ConvertFrom-Csv in PowerShell

Welcome back to Wahmans PowerShell Blog! Today, we’re diving into a handy cmdlet that transforms text-based data into rich PowerShell objects: ConvertFrom-Csv.

According to Microsoft’s official documentation, this cmdlet “Converts object properties in character-separated value (CSV) format into CSV versions of the original objects“. This means that whenever you’re working with data in CSV format—and that’s pretty often—you can use ConvertFrom-Csv to turn that data into usable, script-friendly PowerShell objects.

Basic Syntax

ConvertFrom-Csv [-InputObject] <string[]>

This cmdlet takes CSV formatted data and transforms each row into a PowerShell object where columns become properties.

Examples

1. Beginner – Convert a Simple CSV String

Let’s say you have a simple CSV string in your script:

$csvData = @"
Name,Age,Role
Alice,30,Engineer
Bob,25,Designer
"@

$objects = $csvData | ConvertFrom-Csv
$objects

This will output:

Name  Age Role
----  --- ----
Alice 30  Engineer
Bob   25  Designer

Each line has become a PowerShell object. You can now access properties like $objects[0].Name or loop over them!

2. Intermediate – Import CSV File and Convert

This one reads from a CSV file and converts the text:

$csvText = Get-Content -Path ".\employees.csv"
$employees = $csvText | ConvertFrom-Csv
$employees | ForEach-Object { Write-Host "$($_.Name) is a $_.Role." }

If employees.csv contains rows like "Name,Age,Role", you’ll see formatted output of each employee.

3. Advanced – Convert CSV from REST API Response

Sometimes REST endpoints return CSV text. You can transform it like so:

$response = Invoke-RestMethod -Uri "https://example.com/data.csv" -Method Get
$objects = $response -split "\n" | ConvertFrom-Csv
$objects | Where-Object { $_.Status -eq 'Active' }

Now you can filter and process data from an API in convenient object form!

4. Advanced Pro – Combine CSV Parsing with Custom Object Mapping

You can transform messy CSV headers into cleaner property names:

$csvContent = @"
First Name,Last Name,Department Code
John,Doe,HR
Jane,Smith,IT
"@

$objects = $csvContent | ConvertFrom-Csv | ForEach-Object {
    [PSCustomObject]@{
        FirstName = $_."First Name"
        LastName = $_."Last Name"
        Department = $_."Department Code"
    }
}

$objects

This way you normalize property names for easier downstream processing.

Wrap-Up

ConvertFrom-Csv is essential in any PowerShell scripter’s toolkit for transforming flat CSV into flexible, readable, and manipulatable objects.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *