转换System.Object []和取消引用属性

时间:2019-05-18 13:48:04

标签: powershell scripting azure-cli

Azure CLI返回不方便使用的System.Object []。例如,我可以使用脚本创建App-Insights,az cli返回包含工具密钥的System.Object []。我可以编写一些方法来遍历数组并提取必填字段,但是必须有一种更简单的方法

我试图将对象转换为不同的格式,但是我找不到将cli命令的结果转换为具有可取消引用的属性的对象的可能性

$a = az monitor app-insights component show -a myfuntions -g my-group
$a

{
  "appId": "<id>",
  "applicationId": "myfunctions",
  "applicationType": "web",
  "creationDate": "2019-05-17T15:22:05.042607+00:00",
  "etag": "\"8000ece5-0000-0200-0000-4edfe57e0000\"",
  "flowType": "Bluefield",
  "hockeyAppId": null,
  "hockeyAppToken": null,
  "id": "/subscriptions/1111111-4d7d-4df4-8dae-5311111111/resourceGroups/dev-api/providers/microsoft.insights/components/dev-validierung-functions"
  "instrumentationKey": "3232323-23e05-32da-bf03-a8b8b4d18783",
  "kind": "web",
  "location": "westeurope",
  "name": "myfunctions",
  "provisioningState": "Succeeded",
  "requestSource": "rest",
  "resourceGroup": "mygroup",
  "samplingPercentage": null,
  "tags": {},
  "tenantId": "<the tenant id>",
  "type": "microsoft.insights/components"
}

变量$ a包含System.Object []。可以在自定义函数中遍历数组中的所有对象,但是我想我缺少一些细节。必须有一种简单的方法可以转换为可取消引用的对象。

2 个答案:

答案 0 :(得分:1)

您可以使用PsObject属性:

$object = @"
{
"appId": "<id>",
"applicationId": "myfunctions",
"applicationType": "web",
"creationDate": "2019-05-17T15:22:05.042607+00:00",
"etag": "\"8000ece5-0000-0200-0000-4edfe57e0000\"",
"flowType": "Bluefield",
"hockeyAppId": null,
"hockeyAppToken": null,
"id": "/subscriptions/1111111-4d7d-4df4-8dae-5311111111/resourceGroups/dev-api/providers/microsoft.insights/components/dev-validierung-functions",
"instrumentationKey": "3232323-23e05-32da-bf03-a8b8b4d18783",
"kind": "web",
"location": "westeurope",
"name": "myfunctions",
"provisioningState": "Succeeded",
"requestSource": "rest",
"resourceGroup": "mygroup",
"samplingPercentage": null,
"tags": {},
"tenantId": "<the tenant id>",
"type": "microsoft.insights/components"
}
"@

$j = $object | ConvertFrom-Json
$j.PsObject.Properties | % { Write-Host "Name $($_.Name) ; Value $($_.Value)"}

输出:

Name appId ; Value <id>
Name applicationId ; Value myfunctions
Name applicationType ; Value web
Name creationDate ; Value 2019-05-17T15:22:05.042607+00:00
Name etag ; Value "8000ece5-0000-0200-0000-4edfe57e0000"
Name flowType ; Value Bluefield
Name hockeyAppId ; Value
Name hockeyAppToken ; Value
Name id ; Value /subscriptions/1111111-4d7d-4df4-8dae-5311111111/resourceGroups/dev-api/providers/microsoft.insights/components/dev-validierung-functions
Name instrumentationKey ; Value 3232323-23e05-32da-bf03-a8b8b4d18783
Name kind ; Value web
Name location ; Value westeurope
Name name ; Value myfunctions
Name provisioningState ; Value Succeeded
Name requestSource ; Value rest
Name resourceGroup ; Value mygroup
Name samplingPercentage ; Value
Name tags ; Value
Name tenantId ; Value <the tenant id>
Name type ; Value microsoft.insights/components

希望有帮助。

答案 1 :(得分:0)

从json转换。

$obj = $a | convertfrom-json