使用 PowerShell 创建 JSON 策略文档

Create a JSON policy document using PowerShell

我想创建一个 JSON 策略文档并在 PowerShell 中创建一个自定义对象,稍后可以将其转换为 JSON。

function Add-ObjectContent {
  param(
      $InputObject,
      $Property,
      $Value
  )
  process{
      [array]$path = $Property -split "\."
      If ($Path.Count -gt 1) {
          $Obj = New-Object PSCustomObject
          Add-ObjectContent -InputObject $Obj -Property ($path[1..($path.count - 1)] -join ".") -Value $Value
      }
      else {
          $Obj = $Value
      }
        $InputObject | Add-Member NoteProperty -Name $path[0] -Value $Obj
    }
}

$jsonPolicy = New-Object -TypeName PSCustomObject
Add-ObjectContent -Property "properties.workLoadType" -InputObject $jsonPolicy -Value "SQLDataBase"
Add-ObjectContent -Property "properties.settings.timeZone" -InputObject $jsonPolicy -Value "Eastern Standard Time"
Add-ObjectContent -Property "properties.settings.isCompression" -InputObject $jsonPolicy -Value $true

$jsonPolicy | ConvertTo-JSON

再次添加同一个成员失败。如果存在,是否可以向同一个成员添加多个值?

你不能用你的函数编码方式来做到这一点,因为你总是写入相同的路径。

在编写嵌套对象时,您必须传入现有路径的完整路径并通过输入对象追加。

示例:

function Add-ObjectContent 
{
  param
  (
      $InputObject,
      $Property,
      $Value
  )

  process
  {
      [array]$path = $Property -split '\.'

      If ($Path.Count -gt 1) 
      {
          $Obj = New-Object PSCustomObject

            $AddObjectContentSplat = @{
                InputObject = $Obj
                Property    = ($path[1..($path.count - 1)] -join ".")
                Value       = $Value
            }
            Add-ObjectContent @AddObjectContentSplat
      }
      else 
      {
          $Obj = $Value
      }

        $InputObject | 
        Add-Member NoteProperty -Name $path[0] -Value $Obj
    }
}

$jsonPolicy = New-Object -TypeName PSCustomObject

$ViewJson = {
    $jsonPolicy | 
    ConvertTo-JSON
}

&$ViewJson
# Results
<#
{}
#>

Add-ObjectContent -Property 'properties.workLoadType' -InputObject $jsonPolicy -Value 'SQLDataBase'

&$ViewJson
# Results
<#
{
  "properties": {
    "workLoadType": "SQLDataBase"
  }
}

#>
Add-ObjectContent -Property 'settings.timeZone' -InputObject $jsonPolicy.properties -Value 'Eastern Standard Time'

&$ViewJson
# Results
<#
{
  "properties": {
    "workLoadType": "SQLDataBase",
    "settings": {
      "timeZone": "Eastern Standard Time"
    }
  }
}
#>

Add-ObjectContent -Property 'isCompression' -InputObject $jsonPolicy.properties.settings -Value $true

&$ViewJson
# Results
<#
{
  "properties": {
    "workLoadType": "SQLDataBase",
    "settings": {
      "timeZone": "Eastern Standard Time",
      "isCompression": true
    }
  }
}
#>

所以,如果您想像原来那样传递项目,...

Add-ObjectContent -Property "properties.workLoadType" -InputObject $jsonPolicy -Value "SQLDataBase"

...然后您需要重构该函数以执行上述操作,或者只保留您的函数并利用上述方法。