Understanding ConvertFrom-Csv in PowerShell
Welcome back to Wahmans PowerShell Blog! Today, we’re diving into a useful cmdlet for parsing text-based data: ConvertFrom-Csv
.
The official Microsoft description for ConvertFrom-Csv
is: “Converts object properties in character-separated value (CSV) format into CSV versions of the original objects.” Simply put, this cmdlet allows you to turn a block of comma-separated values into proper PowerShell objects which you can manipulate and work with easily.
Why Use ConvertFrom-Csv?
CSV data is everywhere—logs, data exports, configuration reports, you name it. Instead of manually parsing text files, PowerShell can instantly convert this string data into structured objects, leading to more effective scripting.
Example 1: Simple CSV String Conversion (Beginner)
$csvData = @"
Name,Age,Department
Alice,30,HR
Bob,25,IT
"@
$employees = $csvData | ConvertFrom-Csv
$employees | Format-Table -AutoSize
In this example, a CSV string is turned into PowerShell objects. We use Format-Table
to display the structured data.
Example 2: Import Raw CSV Text From a File
$rawCsv = Get-Content -Path "employees.csv" | Out-String
$employees = $rawCsv | ConvertFrom-Csv
foreach ($emp in $employees) {
Write-Host "$($emp.Name) works in $($emp.Department)"
}
This is helpful when you want to control how CSV content is read into PowerShell versus using Import-Csv
.
Example 3: Convert Non-Standard Delimiters (Intermediate)
$data = @"
Name|Age|Location
Sarah|28|Berlin
Mark|34|London
"@
$people = $data | ConvertFrom-Csv -Delimiter '|'
$people | Format-List
Here we read CSV data using a pipe (|
) as a custom delimiter. This can happen frequently when dealing with exports from legacy systems.
Example 4: Joining Data with ConvertFrom-Csv and REST APIs (Advanced)
$csvInput = @"
Id,Role
101,Manager
102,Developer
"@
$userRoles = $csvInput | ConvertFrom-Csv
foreach ($user in $userRoles) {
$apiData = Invoke-RestMethod -Uri "https://jsonplaceholder.typicode.com/users/$($user.Id)"
[PSCustomObject]@{
Name = $apiData.name
Role = $user.Role
Email = $apiData.email
}
} | Format-Table -AutoSize
This advanced example shows how you can merge CSV content with external API results to enrich your data structures dynamically.
Wrapping Up
ConvertFrom-Csv
is a handy tool for transforming plain-text data into structured objects. Whether you’re at the beginning of your PowerShell journey or building advanced integration scripts, this cmdlet deserves a place in your toolkit.
Happy scripting, and I will see you in the next post!
Leave a Reply