如何使用 PowerShell 将 JSON 文件转换为 CSV 文件?


要使用 PowerShell 将 JSON 文件转换为 CSV 文件,我们需要使用ConvertTo-CSV命令作为管道。

例如,我们有一个名为PatchingServer.JSON的 JSON 文件,存储在 C:\temp 中,其内容如下。

示例

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

我们需要将上述文件转换为 CSV 文件,因此我们将使用ConvertTo-CSV命令,但在此之前,我们需要将 JSON 文件从 JSON 格式转换为表格格式,使用ConvertFrom-JSON,以便ConvertTo-CSV命令可以将其转换为可读格式。

示例

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

输出

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

所以最终的命令应该是:

示例

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

输出

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

使用最后一个命令,表将转换为头和值。我们也可以保存此 CSV 文件。

示例

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

输出

更新时间:15-Dec-2020

22,000+ 次浏览

开启你的职业生涯

完成课程获取认证

开始
广告
© . All rights reserved.