03 / FILES AND FORMATS · LESSON 11

Turn a CSV into a report

Import CSV records, filter them, and export a useful subset.

12 min · learn at your pace

Rows become objects

A CSV file stores tabular data. The first line normally names the columns. Import-Csv turns each remaining row into an object with those property names.

$devices = Import-Csv './devices.csv'
$devices | Get-Member

CSV values are imported as strings. Cast numeric columns before numeric operations, for example [int]$_.AgeDays.

Keep the structure

$devices |
    Where-Object Status -eq 'Offline' |
    Export-Csv './offline.csv' -NoTypeInformation

Export-Csv handles quoting and separators. Do not build CSV rows by joining values with commas: a value might itself contain a comma or quote.

Export objects before applying Format-Table. Formatting produces display instructions rather than the records you intended to save.

The lesson has already provided devices.csv in your workspace. Use the terminal to inspect it with Get-Content, then compare that raw text with the objects returned by Import-Csv.

Try an example.ps1
Import-Csv './devices.csv'
YOUR TURN

Put it into practice.

Read devices.csv, keep the Offline devices, and export those complete records to offline.csv with Name, Status, and Owner preserved.

See an explained solution
One way to solve it.ps1
Import-Csv './devices.csv' |
    Where-Object Status -eq 'Offline' |
    Export-Csv './offline.csv' -NoTypeInformation

CSV import creates structured records. Filtering preserves their properties, and Export-Csv serialises the two selected records correctly.