【问题标题】:powershell output not array type but string type?powershell输出不是数组类型而是字符串类型?
【发布时间】:2022-01-02 13:06:39
【问题描述】:

您好,我正在编写一个脚本来调用 AZ 迁移 api

        $siteuri= 'https://management.azure.com/subscriptions/' + $metadata.compute.subscriptionID +'/resourceGroups/' + $AzMigreateResourceGroup+ '/providers/Microsoft.Migrate/migrateProjects/' + $ProjectName + '/solutions/Servers-Discovery-ServerDiscovery?api-version=2018-09-01-preview'
        $siteoutput=(Invoke-RestMethod -Headers $Authtoken -uri $siteuri).properties.details.extendeddetails.applianceNameToSiteIdMapV3

我得到的结果是这样的

[
  {
    "lab3dev-app01": {
      "ApplianceName": "xxx",
      "SiteId": "xxx",
      "KeyVaultId": "xxx",
      "KeyVaultUrl": "xxx",
      "ApplianceDetails": {
        "machineID": "xxx",
        "IPAddress": "192.168.50.210",
        "HostName": "WIN-ETP6NTN8B65",
        "isRegistered": true,
        "discoveryStatus": "Success",
        "deepDiscoveryDisabled": false
      },
      "CertificateContents": {
        "xxx": ""
      },
      "AadAppDetails": {
        "TenantID": "xxx",
        "AppName": "xxx",
        "AppID": "xxx",
        "ObjectID": "xxx"
      },
      "ScaleOutList": null,
      "isV2Site": false
    }
  },
  {
    "l3devhyper01": {
      "ApplianceName": "xxx",
      "SiteId": "xxx",
      "KeyVaultId": "xxx",
      "KeyVaultUrl": "xxx",
      "ApplianceDetails": {
        "machineID": "xxx",
        "IPAddress": "192.168.50.143",
        "HostName": "WIN-PKKCDSLE6OD",
        "isRegistered": true,
        "discoveryStatus": "Success",
        "deepDiscoveryDisabled": false
      },
      "CertificateContents": {
        "l3devhyper017a74agentauthcertv2": ""
      },
      "AadAppDetails": {
        "TenantID": "xxx",
        "AppName": "xxx",
        "AppID": "xxx",
        "ObjectID": "xxx"
      },
      "ScaleOutList": null,
      "isV2Site": false
    }
  }
]

我希望这可以是一个数组类型,所以我可以做一些搜索,但是 gettype() 告诉我这是一个字符串?

有没有办法把它输出为数组而不是字符串?

【问题讨论】:

  • 这是一个 JSON 字符串。使用ConvertFrom-Json 将其转换为对象。

标签: azure powershell


【解决方案1】:

Invoke-RestMethod 确实返回一个对象,您甚至可以使用它来访问特定属性。您需要查看 API 描述以了解它是否只是一个字符串属性(可能是这种情况)。

您可以从该字符串中看到它是一个 JSON 对象,您可以使用 ConvertFrom-Json 将其转换为一个对象。

没有额外错误处理的最简单的情况是:

$siteoutput = Invoke-RestMethod -Headers $Authtoken -uri $siteuri
$siteoutput = $siteoutput.properties.details.extendeddetails.applianceNameToSiteIdMapV3 | ConvertFrom-Json

【讨论】:

    猜你喜欢
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2020-02-23
    • 1970-01-01
    相关资源
    最近更新 更多