How to convert JSON file to CSV file using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To convert the JSON file to the CSV file using PowerShell, we need to use the ConvertTo-CSV command as a pipeline.

For example, we have a JSON file called PatchingServer.JSON stored at C:\temp and its content is as below.

Example

PS C:\> Get-Content C:\Temp\PatchingServer.json
{
   "Port": "9000",
   "ApplicationName": "TestApp",
   "MaintenanceWindow": "Every Saturday",
   "BusinessUnit": "IT",
   "AppOwner": "Josh",
   "AppID": "1jj2221-223443s",
   "Location": "EastUS"
}

We need to convert the above file to the CSV file so we will use the ConvertTo-CSV command but before that, we need the JSON file need to be converted from JSON format to table format using ConvertFrom-JSON so the ConvertTo-CSV command can make it into a readable format.

Example

PS C:\> Get-Content C:\Temp\PatchingServer.json |ConvertFrom-Json

Output

Port              : 9000
ApplicationName   : TestApp
MaintenanceWindow : Every Saturday
BusinessUnit      : IT
AppOwner          : Josh
AppID             : 1jj2221-223443s
Location          : EastUS

So the final command should be,

Example

Get-Content C:\Temp\PatchingServer.json | ConvertFrom-Json | ConvertTo-Csv

Output

"Port","ApplicationName","MaintenanceWindow","BusinessUnit","AppOwner","AppID","Location"
"9000","TestApp","Every Saturday","IT","Josh","1jj2221-223443s","EastUS"

With the last command, the table is converted to the headers and values. We can save this CSV file as well.

Example

Get-Content C:\Temp\PatchingServer.json | ConvertFrom-Json | ConvertTo-Csv | Out-File C:\Temp\Patching.csv

Output

raja
Published on 15-Dec-2020 12:18:30
Advertisements