如何使用 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
輸出
廣告