PowerShell travaille avec des objets. Pour les sauvegarder dans un format lisible par d’autres outils (JavaScript, APIs, applications web…), on utilise le JSON.
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 :
ConvertTo-JsonOut-File ou Set-Content<commande> | ConvertTo-Json | Out-File "data.json"
Exemple simple :
Get-Process | ConvertTo-Json | Out-File "processus.json"
Comme pour Export-Csv, on utilise Select-Object pour simplifier.
Get-ChildItem -File |
Select-Object Name, Length, LastWriteTime |
ConvertTo-Json |
Out-File "fichiers.json"
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"
ConvertTo-Json | Out-File "data.json" -Encoding utf8
| 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 |
Il n’existe pas de cmdlet Export-Json par défaut dans PowerShell.
La combinaison correcte est toujours :
ConvertTo-Json → Out-File