Loading
0x70Lesson 8 of 17

CSV, JSON and formatting

Import and export CSV and JSON, shape objects with calculated properties, and format output for people.

28 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • Read and write CSV with Import-Csv, Export-Csv and their ConvertFrom/ConvertTo cousins
  • Convert objects to and from JSON, and avoid the depth and single-item traps
  • Add calculated properties with Select-Object, and format output with Format-Table and Format-List

Because PowerShell works with objects, converting between files and data is one command each way:

FormatReadWrite
CSV fileImport-Csv dragons.csvExport-Csv dragons.csv -NoTypeInformation
CSV textConvertFrom-CsvConvertTo-Csv
JSON textConvertFrom-JsonConvertTo-Json
JSON from a web APIInvoke-RestMethod https://...
PowerShell’s own formatImport-ClixmlExport-Clixml (keeps types)

-NoTypeInformation is the default in PowerShell 7; Windows PowerShell 5.1 adds an extra #TYPE line without it. Remember: everything that comes out of a CSV is a string.

csv-and-json.ps1
1$dragons = @'
2Name,Wingspan
3Ember,12
4Glim,2
5'@ | ConvertFrom-Csv
6$dragons[0].Wingspan.GetType().Name
7$dragons | ConvertTo-Json -Compress
8$feeding = '{"keeper":"Ada","meals":[{"dragon":"Ember","kg":40},{"dragon":"Glim","kg":1}]}' | ConvertFrom-Json
9$feeding.keeper
10($feeding.meals | Measure-Object -Property kg -Sum).Sum
11$feeding.meals[0].dragon
Output
String
[{"Name":"Ember","Wingspan":"12"},{"Name":"Glim","Wingspan":"2"}]
Ada
41
Ember

ConvertFrom-Json gives you objects with real numbers and nested arrays - dot right into them. Calling a web API works the same way: Invoke-RestMethod fetches and converts in one step:

$weather = Invoke-RestMethod "https://api.example.com/forecast?city=Emberfall"
$weather.daily | Where-Object { $_.rain -gt 5 } | Select-Object date, rain

Calculated properties

Select-Object can invent properties. Instead of a property name, give a hashtable with a Name and an Expression script block. This is how you fix types, rename columns and add computed values before exporting:

calculated.ps1
1$dragons = @'
2Name,Wingspan,Age
3Ember,12,140
4Glim,2,12
5Skyla,15,88
6'@ | ConvertFrom-Csv
7$dragons |
8  Select-Object Name,
9    @{ Name = 'Wingspan'; Expression = { [int]$_.Wingspan } },
10    @{ Name = 'Category'; Expression = { if ([int]$_.Age -ge 100) { 'elder' } else { 'young' } } } |
11  ConvertTo-Csv -NoTypeInformation
Output
"Name","Wingspan","Category"
"Ember","12","elder"
"Glim","2","young"
"Skyla","15","young"

Formatting for people

When objects reach the end of the pipeline, PowerShell picks a view: a table for up to four properties, a list for more. You can choose:

  • Format-Table Name, Wingspan -AutoSize - columns, sized to fit
  • Format-List * - one property per line, all properties
  • Out-String - the formatted text as a string

The Format-* cmdlets produce display instructions, not data - which is why they always go last. $x | Format-Table | Export-Csv writes garbage.

format.ps1
1$ember = [pscustomobject]@{ Name = 'Ember'; Species = 'Firedrake'; Wingspan = 12 }
2$glim = [pscustomobject]@{ Name = 'Glim'; Species = 'Wisp'; Wingspan = 2 }
3$ember, $glim | Format-Table Name, Wingspan
4$ember | Format-List
Output

Name  Wingspan
----  --------
Ember       12
Glim         2


Name     : Ember
Species  : Firedrake
Wingspan : 12

Key takeaways

  • Import-Csv/ConvertFrom-Csv and ConvertFrom-Json turn text into objects; Export-Csv and ConvertTo-Json go back.

  • CSV values are strings; JSON keeps numbers. Use -Depth and @( ) with ConvertTo-Json.

  • Calculated properties, @{ Name = ...; Expression = { ... } }, reshape objects in Select-Object.

  • Format-Table and Format-List are for display only - always last.

Lesson quiz

7 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write PowerShell scripts

Write a script in the editor and run it for real against sample input, which is piped into your script as $input. Scripts run on PowerShell 6.2 through Try It Online (tio.run), a free public service, so these exercises avoid PowerShell 7-only syntax; your script and test input are sent there.

Exercise 1

Roster to JSON

+25 XP

The input is the dragon roster as CSV. Output compact JSON - always an array - of objects with just Name and Wingspan, where Wingspan is a number, for dragons with a wingspan of 10 m or more, largest first:

[{"Name":"Skyla","Wingspan":15},{"Name":"Ember","Wingspan":12},{"Name":"Vesper","Wingspan":11}]
  • The residents
  • The visitors
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Exercise 2

Meal summary from JSON

+25 XP

The input is a JSON feeding report (possibly over several lines). Print the keeper, the total kilograms, and the dragon that ate the most:

Keeper: Ada
Total: 47 kg
Hungriest: Ember (40 kg)
  • Ada’s report
  • Grace’s report
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: