← PowerShell course
6

Files, CSV & JSON

25 min

Turn raw server data into polished reports. Import CSV as objects, reshape and filter them, add calculated columns, export clean CSV, and parse JSON configs.

By the end you can
  • Read files with Get-Content and understand when to use Import-Csv instead
  • Understand that Import-Csv returns objects — one per row, columns as properties
  • Filter and shape imported objects with Where-Object and Select-Object
  • Add calculated properties (e.g. FreeGB from bytes) using Select-Object hash tables
  • Export clean CSV reports with Export-Csv -NoTypeInformation and parse JSON with ConvertFrom-Json

Files, CSV & JSON

Infra teams live in spreadsheets and config files. PowerShell's superpower is treating those files not as text — but as objects.

Reading files: Get-Content

Get-Content reads any file and returns an array of strings, one per line:

Get-Content C:\Logs\app.log -Tail 20

For structured data (CSV, JSON) you almost always want a smarter cmdlet.

The key insight: Import-Csv returns OBJECTS

Given a file servers.csv with a header row, Import-Csv does not give you lines of text. It gives you one object per row, where each column header becomes a property:

Import-Csv .\servers.csv | Get-Member
# TypeName: System.Management.Automation.PSCustomObject
# Properties: Name, Environment, DiskFreeBytes, Role

That means you can pipe straight into Where-Object, Select-Object, Sort-Object — exactly like Get-Process output.

Filtering and calculated properties

CSV properties are always strings, so numeric maths needs a cast. Select-Object lets you add a calculated column using a hash table with Name and Expression keys:

Import-Csv .\servers.csv |
    Where-Object { $_.Environment -eq 'Production' } |
    Select-Object Name, Role,
        @{ Name = 'FreeGB'; Expression = { [math]::Round([long]$_.DiskFreeBytes / 1GB, 1) } }

Exporting CSV reports

... | Export-Csv -Path .\report.csv -NoTypeInformation

-NoTypeInformation removes the ugly #TYPE comment line. Always include it.

JSON: ConvertTo-Json and ConvertFrom-Json

$config = '{"AlertThresholdGB":20,"NotifyEmail":"ops@contoso.com"}' | ConvertFrom-Json
$config.AlertThresholdGB   # 20

ConvertFrom-Json returns a PSCustomObject, so you access values with dot-notation just like any other PowerShell object.