Powershell脚本将JSON变量文件转换为CSV

时间:2019-10-23 09:11:31

标签: json powershell

我是Powershell的新手,所以请原谅我可能遇到的任何错误。 我需要编写一个Powershell脚本将JSON变量文件转换为CSV。 我需要遍历文件,并选择“名称”和“ Id”字段的所有变量。

首先我将json文件转换为String。但是我不确定如何遍历json文件并选择任何Name字段项。然后,我将其导出到一个csv文件中。

这会将json文件转换为字符串

$data = (Get-Content "C:\Users\QVL6\Downloads\express-ordering-web- 
variables.json" | ConvertFrom-Json)

这会将其导出到一个csv文件中:

 $data | Select-Object -Name,  Description | Export -Csv -Path .\data.csv 
 -  NoClobber -NoTypeInformation

对于每个循环,我都需要帮助,该循环将遍历文件并将任何Name字段值放置到csv文件的标题下。

以下是json文件的前3个对象:

{
      "Id": "f73bdd3d-0449-036d-c2b6-b5fde280b05f",
      "Name": "CIFolderPermissionGroup",
      "Description": null,
      "Scope": {},
      "IsEditable": true,
      "Prompt": null,
      "Type": "String",
      "IsSensitive": false
    },
    {
      "Id": "f138f849-1647-4346-6ac4-cee4bdbd808a",
      "Name": "CustomInstallFolder",
      "Value": "c:\\inetpub\\wwwroot",
      "Description": null,
      "Scope": {},
      "IsEditable": true,
      "Prompt": null,
      "Type": "String",
      "IsSensitive": false
    },
    {
      "Id": "99d478fb-6ef3-cc21-7997-4a9b12f3ad00",
      "Name": "eimasConfiguartion",
      "Value": "{\"issuelocal/":true}",
      "Description": null,
      "Scope": {
        "Environment": [
          "Environments-63"
        ]
    }

到目前为止,这是我的代码:     $ json =(获取内容“ C:\ Users \ QVL6 \ Downloads \ express-ordering-web-     variables.json” | ConvertFrom-Json)

# helper to turn PSCustomObject into a list of key/value pairs
function Get-ObjectMembers {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True, ValueFromPipeline=$True)]
        [PSCustomObject]$obj
)
$obj | Get-Member -MemberType NoteProperty | ForEach-Object {
    $key = $_.Name
    [PSCustomObject]@{Key = $key; Value = $obj."$key"}
}

}

#Produce a list of output objects with Name, Type, Value and Description

$ | ConvertFrom-Json | Get-ObjectMembers | foreach {
   $_.Value | Get-ObjectMembers | where Key -match "Name" | foreach {
        [PSCustomObject]@{
            Name = $_.value.data.value | select 
            Type = $_.Value.data | value | select 
            Value = $_.Value.data | value | select 
            Description = $_.Value.data | value | select    
        }
    }
}


$path = C:\Users\QVL6\
$data | Select-ObjectMambers -Property Name, Type, Value, Description | 
Export -Csv -Path .\data.csv -NoClobber -NoTypeInformation

0 个答案:

没有答案