PowerShell嵌套JSON vSphere路径文件夹

时间:2018-10-16 03:12:53

标签: powershell powercli

我有一个PowerShell脚本,可以在vSphere环境中生成VM对象的JSON输出。每个VM都有一个path属性,该属性代表VM在文件夹结构中的位置。不是将文件夹表示为属性,而是如何修改脚本以使用路径值生成带有嵌套VM对象的文件夹对象?

示例PowerShell脚本

$SQL = "USE $SQLDatabase SELECT top 2 * FROM VMs"
$computers = Invoke-sqlcmd -query $SQL -ServerInstance $SQLInstance -Username $SQLUsername -Password $SQLPassword

$connections = @()
$customProperties = @()

ForEach ($computer in $computers) {

    $connection = New-Object pscustomobject -Property @{
        "Type" = $computer.Type;
        "Name" = $computer.Name
        "ComputerName" = $computer.ComputerName
        "Path" = $computer.$path

    }
    $connections += $connection
}

@{
    Objects = $connections
} |
ConvertTo-Json -Depth 100 |
Write-Host]

电流输出

{
  "Objects": [
    {
      "Path": "Clients A-K/Client 1 (ACC)",
      "ComputerName": "VM1",
      "Name": "VM1",
      "Type": "TerminalConnection"
    },
    {
      "Path": "Clients A-K/Client 1(ACC)",
      "ComputerName": "VM2",
      "Name": "VM2",
      "Type": "RemoteDesktopConnection"
    }
  ]
}

目标输出

{
  "Objects": [
    {
      "Type": "Folder",
      "Name": "Clients A-K",
      "Objects": [
        {
          "Type": "Folder",
          "Name": "Client 1 (ACC)",
          "Objects": [
            {
              "Type": "TerminalConnection",
              "Name": "VM1",
              "ComputerName": "VM1",
            },
            {
              "Type": "RemoteDesktopConnection",
              "Name": "VM2",
              "ComputerName": "VM2",
            }
          ]
        }
      ]
    }
  ]
}

0 个答案:

没有答案