PowerShell – `ConvertTo-Json` : exporter un fichier JSON

PowerShell travaille avec des objets. Pour les sauvegarder dans un format lisible par d’autres outils (JavaScript, APIs, applications web…), on utilise le JSON.

    6tq
  • niveau

Le JSON est aujourd’hui un format standard, très utilisé pour l’échange de données.

Dans PowerShell, l’export JSON se fait en deux étapes :

  1. Convertir les objets en JSONConvertTo-Json
  2. Écrire le fichierOut-File ou Set-Content

Syntaxe de base

<commande> | ConvertTo-Json | Out-File "data.json"

Exemple simple :

Get-Process | ConvertTo-Json | Out-File "processus.json"

Choisir les propriétés avant export

Comme pour Export-Csv, on utilise Select-Object pour simplifier.

Get-ChildItem -File |
    Select-Object Name, Length, LastWriteTime |
    ConvertTo-Json |
    Out-File "fichiers.json"

Export lisible (indenté)

ConvertTo-Json génère déjà un JSON indenté, mais on peut augmenter la profondeur d’objets avec -Depth.

Get-Service | ConvertTo-Json -Depth 5 | Out-File "services.json"

Exporter en UTF-8 (conseillé)

ConvertTo-Json | Out-File "data.json" -Encoding utf8

Résumé

Besoin Commande
Export JSON simple `… ConvertTo-Json Out-File "data.json"`
Sélectionner les colonnes Select-Object avant
Gérer la profondeur ConvertTo-Json -Depth 5
Encodage propre Out-File -Encoding utf8

Remarque importante

Il n’existe pas de cmdlet Export-Json par défaut dans PowerShell. La combinaison correcte est toujours :

ConvertTo-Json → Out-File

Pour aller plus loin