PowerShell turns CSV and JSON into objects. Import-Csv and ConvertFrom-Json read data into objects you can filter, sort, and change with the usual cmdlets, and Export-Csv and ConvertTo-Json write them back out. That makes PowerShell an easy bridge between spreadsheets, configuration files, and web APIs.

IT work is full of both formats. HR sends a CSV of new hires, an inventory tool exports a CSV of computers, an application keeps its settings in a JSON file, and every web API answers in JSON. Because PowerShell works with objects instead of text, you can read either format, work with it using the same commands you already know, and save it in the other format in a line or two.

This guide shows how to read, filter, summarize, modify, and export CSV and JSON data, how to convert between them, and the pitfalls that catch almost everyone the first time. If you’re new to PowerShell, start with PowerShell: A Beginner’s Guide for IT Administrators.

Follow along: download computers.csv and settings.json from the data repository on GitHub into one folder, and open PowerShell 7 in that folder. The examples were tested in PowerShell 7.6, and most also work in Windows PowerShell 5.1.

Part 1: CSV Files

computers.csv is a small inventory with one row per computer:

Name,Department,OS,RamGB,LastSeen
PC-ACCT-01,Finance,Windows 11,16,2026-11-20
PC-ACCT-02,Finance,Windows 10,8,2026-09-02
PC-IT-01,IT,Windows 11,32,2026-11-27
PC-IT-02,IT,Windows 11,16,2026-11-26
PC-SALES-01,Sales,Windows 10,8,2026-10-15
PC-SALES-02,Sales,Windows 11,16,2026-11-25
PC-SALES-03,Sales,Windows 10,4,2026-06-30

Reading a CSV With Import-Csv

$computers = Import-Csv -Path ./computers.csv
$computers | Format-Table
Name        Department OS         RamGB LastSeen
----        ---------- --         ----- --------
PC-ACCT-01  Finance    Windows 11 16    2026-11-20
PC-ACCT-02  Finance    Windows 10 8     2026-09-02
PC-IT-01    IT         Windows 11 32    2026-11-27
PC-IT-02    IT         Windows 11 16    2026-11-26
PC-SALES-01 Sales      Windows 10 8     2026-10-15
PC-SALES-02 Sales      Windows 11 16    2026-11-25
PC-SALES-03 Sales      Windows 10 4     2026-06-30

Import-Csv uses the first line as column names and turns every other line into an object with those names as properties. You can use each row like any other object:

$computers[0]
Name       : PC-ACCT-01
Department : Finance
OS         : Windows 11
RamGB      : 16
LastSeen   : 2026-11-20

$computers.Count returns 7, one object per row.

The Big Catch: Everything Is Text

CSV files have no data types, so Import-Csv makes every value a string, even numbers and dates:

$computers[0].RamGB.GetType().Name
String

That matters as soon as you sort or compare. Here are the “three computers with the most RAM”:

$computers | Sort-Object RamGB -Descending | Select-Object -First 3 Name, RamGB
Name        RamGB
----        -----
PC-ACCT-02  8
PC-SALES-01 8
PC-SALES-03 4

That’s wrong: as text, "8" comes after "32" and "16", because strings are compared character by character. Convert the value to a number while sorting:

$computers | Sort-Object { [int]$_.RamGB } -Descending | Select-Object -First 3 Name, RamGB
Name       RamGB
----       -----
PC-IT-01   32
PC-ACCT-01 16
PC-IT-02   16

When you compare with -lt or -gt, convert too. PowerShell converts the right side to match the left side’s type, so putting the number on the left, or casting with [int], gives a numeric comparison:

$computers | Where-Object { $_.OS -eq "Windows 10" -and [int]$_.RamGB -lt 16 } |
    Select-Object Name, Department, RamGB
Name        Department RamGB
----        ---------- -----
PC-ACCT-02  Finance    8
PC-SALES-01 Sales      8
PC-SALES-03 Sales      4

Converting the Columns Once

Instead of casting in every command, convert the columns when you import, using calculated properties:

$computers = Import-Csv ./computers.csv | Select-Object Name, Department, OS,
    @{ Name = "RamGB";    Expression = { [int]$_.RamGB } },
    @{ Name = "LastSeen"; Expression = { [datetime]$_.LastSeen } }

$computers[0].RamGB.GetType().Name
$computers[0].LastSeen.GetType().Name
Int32
DateTime

Now RamGB sorts and compares as a number, and LastSeen is a real date you can do math with. The rest of this section uses this typed $computers.

Filtering With Dates

Which computers haven’t been seen on the network in more than 30 days? Subtracting two dates gives a time span with a Days property:

$cutoff = [datetime]"2026-11-28"
$computers | Where-Object { ($cutoff - $_.LastSeen).Days -gt 30 } |
    Select-Object Name, @{ Name = "DaysSinceSeen"; Expression = { ($cutoff - $_.LastSeen).Days } }
Name        DaysSinceSeen
----        -------------
PC-ACCT-02             87
PC-SALES-01            44
PC-SALES-03           151

In real use, replace the fixed date with Get-Date to compare against today. Computers that haven’t checked in for weeks may be lost, broken, or missing security updates, and worth a follow-up.

Grouping and Summarizing

Group-Object counts rows by any column, and Measure-Object calculates totals and averages:

$computers | Group-Object OS | Select-Object Name, Count
Name       Count
----       -----
Windows 10     3
Windows 11     4
$computers | Measure-Object -Property RamGB -Sum -Average -Minimum -Maximum
Count             : 7
Average           : 14.2857142857143
Sum               : 100
Maximum           : 32
Minimum           : 4
StandardDeviation :
Property          : RamGB

Combine them to build a summary per department, one custom object per group:

$computers | Group-Object Department | ForEach-Object {
    [PSCustomObject]@{
        Department = $_.Name
        Computers  = $_.Count
        TotalRamGB = [int]($_.Group | Measure-Object -Property RamGB -Sum).Sum
        Windows10  = ($_.Group | Where-Object OS -eq "Windows 10").Count
    }
}
Department Computers TotalRamGB Windows10
---------- --------- ---------- ---------
Finance            2         24         1
IT                 2         48         0
Sales              3         28         2

Inside the loop, $_.Group holds the rows that belong to that department, so you can measure or filter them separately.

Writing a CSV With Export-Csv

Send any objects to Export-Csv to save them as a CSV file, for example a list of computers that need a Windows 11 upgrade:

$computers | Where-Object OS -eq "Windows 10" |
    Select-Object Name, Department, RamGB |
    Export-Csv -Path ./windows10-upgrades.csv -NoTypeInformation
Get-Content ./windows10-upgrades.csv
"Name","Department","RamGB"
"PC-ACCT-02","Finance","8"
"PC-SALES-01","Sales","8"
"PC-SALES-03","Sales","4"

A few options you’ll use often:

  • -NoTypeInformation stops Windows PowerShell 5.1 from adding a #TYPE line at the top. PowerShell 7 leaves it out by default, but including the parameter keeps your script working in both.
  • -Append adds rows to an existing file instead of replacing it, handy for logs that grow over time.
  • -Delimiter ";" reads or writes files that use semicolons, common in countries where the comma is the decimal separator. Import-Csv takes the same parameter.
  • -Encoding utf8BOM (PowerShell 7) helps Excel show accented characters correctly. PowerShell 7 writes UTF-8 without a byte order mark (BOM), and some versions of Excel misread it. In Windows PowerShell 5.1, Export-Csv defaults to ASCII, which turns characters like é into ?, so add -Encoding UTF8 there.

Select the columns you want before exporting, and never pipe Format-Table into Export-Csv: format cmdlets produce formatting instructions, not your data, and the file fills with gibberish.

To get CSV text without writing a file, for example to paste into an email or send to an API, use ConvertTo-Csv:

$computers | Select-Object -First 2 Name, OS | ConvertTo-Csv -NoTypeInformation
"Name","OS"
"PC-ACCT-01","Windows 11"
"PC-ACCT-02","Windows 10"

Files Without a Header Row

Some tools export CSV data with no header line. Give the columns names with -Header:

"web01,443`nweb02,8443" | Set-Content ./ports.txt
Import-Csv -Path ./ports.txt -Header Server, Port
Server Port
------ ----
web01  443
web02  8443

Part 2: JSON Data

JSON is the format of web APIs and many configuration files. settings.json looks like this:

{
  "appName": "Inventory Sync",
  "version": "1.4.0",
  "logging": {
    "level": "Info",
    "path": "C:\\Logs\\inventory.log"
  },
  "servers": [
    { "name": "web01", "port": 443, "enabled": true },
    { "name": "web02", "port": 443, "enabled": false }
  ]
}

Unlike CSV, JSON has nested objects (logging), lists (servers), and real data types: 443 is a number and true is a Boolean.

Reading JSON With ConvertFrom-Json

$settings = Get-Content -Path ./settings.json -Raw | ConvertFrom-Json
$settings.appName
$settings.logging.level
$settings.servers
Inventory Sync
Info

name  port enabled
----  ---- -------
web01  443    True
web02  443   False

Two details:

  • Use -Raw with Get-Content. Without it, Get-Content returns the file as a list of separate lines. -Raw reads it as one string, which is what ConvertFrom-Json expects. (PowerShell 7 copes with lines too, but Windows PowerShell 5.1 doesn’t, so -Raw is the safe habit.)
  • Nested values use dots. $settings.logging.level walks into the logging object. Lists become arrays of objects you can filter like anything else:
$settings.servers | Where-Object enabled | Select-Object -ExpandProperty name
web01

Modifying and Saving JSON

Change properties like any object, then convert back and save:

$settings.logging.level = "Debug"
$settings.servers += [PSCustomObject]@{ name = "web03"; port = 8443; enabled = $true }
$settings | ConvertTo-Json -Depth 5 | Set-Content -Path ./settings.json
Get-Content ./settings.json
{
  "appName": "Inventory Sync",
  "version": "1.4.0",
  "logging": {
    "level": "Debug",
    "path": "C:\\Logs\\inventory.log"
  },
  "servers": [
    {
      "name": "web01",
      "port": 443,
      "enabled": true
    },
    {
      "name": "web02",
      "port": 443,
      "enabled": false
    },
    {
      "name": "web03",
      "port": 8443,
      "enabled": true
    }
  ]
}

The data types survived the round trip: the port is still a number and enabled is still a Boolean. This read-modify-save pattern is a safe way to update configuration files across many servers, much better than search-and-replace on the text. (Back up the file first, as you would before any change you might need to undo.)

The -Depth Trap

ConvertTo-Json only follows nested objects two levels deep by default. Anything deeper is cut off:

$report = [PSCustomObject]@{
    Company = "Contoso"
    Sites   = @(
        [PSCustomObject]@{
            Name    = "El Centro"
            Servers = @( [PSCustomObject]@{ Name = "web01"; Roles = @("IIS", "DNS") } )
        }
    )
}
$report | ConvertTo-Json
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{
  "Company": "Contoso",
  "Sites": [
    {
      "Name": "El Centro",
      "Servers": ""
    }
  ]
}

The server list was lost. PowerShell 7 at least warns you; Windows PowerShell 5.1 truncates silently, which is worse. Always pass -Depth with a number larger than your data needs:

$report = [PSCustomObject]@{
    Company = "Contoso"
    Sites   = @(
        [PSCustomObject]@{
            Name    = "El Centro"
            Servers = @( [PSCustomObject]@{ Name = "web01"; Roles = @("IIS", "DNS") } )
        }
    )
}
$report | ConvertTo-Json -Depth 10
{
  "Company": "Contoso",
  "Sites": [
    {
      "Name": "El Centro",
      "Servers": [
        {
          "Name": "web01",
          "Roles": [
            "IIS",
            "DNS"
          ]
        }
      ]
    }
  ]
}

Compact JSON and Single Items

-Compress removes the spacing, which is useful for logs or sending data to an API:

$computers | Select-Object -First 1 Name, RamGB | ConvertTo-Json -Compress
{"Name":"PC-ACCT-01","RamGB":16}

Notice that a single object becomes a JSON object, not a list. If the receiving system expects a list even when there’s only one item, add -AsArray (PowerShell 7):

$computers | Where-Object Name -eq "PC-IT-01" | Select-Object Name, RamGB | ConvertTo-Json -AsArray -Compress
[{"Name":"PC-IT-01","RamGB":32}]

Reading JSON as a Hashtable

In PowerShell 7, ConvertFrom-Json -AsHashtable returns hashtables instead of objects. That’s useful when keys aren’t valid property names, or when you need to look keys up dynamically:

$config = Get-Content -Path ./settings.json -Raw | ConvertFrom-Json -AsHashtable
$config.GetType().Name
$config["logging"]["level"]
OrderedHashtable
Info

Getting JSON From a Web API

Invoke-RestMethod calls a web API and converts the JSON response into objects for you, so there’s no ConvertFrom-Json step:

$release = Invoke-RestMethod -Uri "https://api.github.com/repos/PowerShell/PowerShell/releases/latest"
$release.tag_name
$release.assets.Count -gt 0

This asks GitHub’s public API for the latest PowerShell release and prints its version tag (v7.7.0 when this was written). Everything you learned above applies to the result: filter it, select properties, and export it to CSV. For APIs that need sign-in, pass a token in -Headers, and keep the token out of your script (use Get-Credential or Microsoft’s SecretManagement module). Whenever you work with someone else’s data, remember the privacy basics.

Part 3: Converting Between CSV and JSON

CSV to JSON

Import, select, and convert:

$computers | Where-Object Department -eq "IT" | Select-Object Name, OS, RamGB | ConvertTo-Json
[
  {
    "Name": "PC-IT-01",
    "OS": "Windows 11",
    "RamGB": 32
  },
  {
    "Name": "PC-IT-02",
    "OS": "Windows 11",
    "RamGB": 16
  }
]

Because the typed import made RamGB an integer, it comes out as a JSON number (32), not a string ("32"). Add | Set-Content computers.json to save it.

JSON to CSV: Flatten First

CSV is flat: one row, one value per column. JSON often isn’t. Converting nested JSON directly gives you useless columns:

$json = '[{ "user": "mlopez", "profile": { "dept": "Finance" }, "groups": ["Staff", "Finance"] }]'
$json | ConvertFrom-Json | ConvertTo-Csv -NoTypeInformation
"user","profile","groups"
"mlopez","@{dept=Finance}","System.Object[]"

@{dept=Finance} and System.Object[] are PowerShell’s text versions of an object and an array. Flatten the data with calculated properties first, pulling nested values up and joining lists into a single string:

$json = @'
[
  { "user": "mlopez", "profile": { "dept": "Finance", "city": "El Centro" }, "groups": ["Staff", "Finance"] },
  { "user": "jcarter", "profile": { "dept": "IT", "city": "Brawley" }, "groups": ["Staff", "IT", "Admins"] }
]
'@
$json | ConvertFrom-Json |
    Select-Object user,
        @{ Name = "Department"; Expression = { $_.profile.dept } },
        @{ Name = "City";       Expression = { $_.profile.city } },
        @{ Name = "Groups";     Expression = { $_.groups -join ";" } } |
    ConvertTo-Csv -NoTypeInformation
"user","Department","City","Groups"
"mlopez","Finance","El Centro","Staff;Finance"
"jcarter","IT","Brawley","Staff;IT;Admins"

This is the pattern for turning almost any API response into a spreadsheet: pick the fields you need, flatten nested objects with dots, and join lists with -join.

Common Mistakes to Avoid

  • Sorting or comparing CSV numbers as text. Cast with [int] or [datetime], or convert the columns once with calculated properties.
  • Forgetting -Depth. ConvertTo-Json silently (in 5.1) or with a warning (in 7) cuts off data deeper than two levels. Use -Depth 10 or more.
  • Reading JSON without -Raw. Use Get-Content -Raw so ConvertFrom-Json gets one string.
  • Exporting formatted output. Format-Table | Export-Csv writes formatting instructions, not data. Use Select-Object instead.
  • Exporting nested objects to CSV. Flatten them first, or you’ll see System.Object[] in your spreadsheet.
  • Ignoring encoding. Accented names can turn into ? or garbled text. Use -Encoding UTF8 in 5.1, and -Encoding utf8BOM in 7 if Excel shows them wrong.
  • Overwriting the original file. Write results to a new file, or back up the original before saving changes over it.

Quick Reference

TaskCommand
Read a CSV fileImport-Csv -Path data.csv
Read a CSV with no headerImport-Csv -Path data.csv -Header Col1, Col2
Read a semicolon-separated fileImport-Csv -Path data.csv -Delimiter ";"
Write a CSV fileExport-Csv -Path out.csv -NoTypeInformation
Add rows to a CSVExport-Csv -Path out.csv -Append -NoTypeInformation
CSV text without a fileConvertTo-Csv -NoTypeInformation
Read a JSON fileGet-Content -Path data.json -Raw | ConvertFrom-Json
Write a JSON fileConvertTo-Json -Depth 10 | Set-Content -Path out.json
Compact JSONConvertTo-Json -Compress
Always output a JSON list (PS 7)ConvertTo-Json -AsArray
JSON as a hashtable (PS 7)ConvertFrom-Json -AsHashtable
Call a JSON APIInvoke-RestMethod -Uri https://...

Frequently Asked Questions

Why are my CSV numbers sorting wrong in PowerShell?

Import-Csv reads every value as text, so "8" sorts after "32". Sort with Sort-Object { [int]$_.Column }, or convert the column to a number with a calculated property when you import.

Why is my JSON missing data after ConvertTo-Json?

ConvertTo-Json stops at two levels deep by default. Add -Depth with a larger number, such as -Depth 10.

What’s the difference between Export-Csv and ConvertTo-Csv?

Export-Csv writes the CSV to a file. ConvertTo-Csv returns the CSV as text, which you can store in a variable, send to an API, or pipe somewhere else.

What’s the difference between Invoke-RestMethod and Invoke-WebRequest?

Invoke-RestMethod converts JSON (and XML) responses into objects automatically, which is what you want for APIs. Invoke-WebRequest returns the full response, including status code, headers, and raw content, which is better for downloading files or checking web pages.

Can PowerShell read Excel files directly?

Not with built-in cmdlets. Save the sheet as CSV and use Import-Csv, or install the community ImportExcel module from the PowerShell Gallery, which reads and writes .xlsx files without Excel installed.

Conclusion

Once CSV and JSON are objects, everything else in PowerShell applies: Where-Object to filter, Sort-Object and Group-Object to organize, Measure-Object to summarize, and calculated properties to reshape. Remember the two classic traps, CSV values are always text and ConvertTo-Json needs -Depth, and flatten nested data before exporting to CSV. With those habits, turning an HR spreadsheet into accounts, an API response into a report, or a settings file into an automated update is just a few lines of PowerShell.