我正在try 访问由Azure Advisor使用PowerShell创建的JSON对象中的特定字段.我有以下对象:
@{id=/subscriptions/xxxx/providers/Microsoft.Advisor/recommendations/xxxx;
category=Cost;
impact=High;
impactedArea=Microsoft.Subscriptions/subscriptions;
description=Consider virtual machine reserved instance to save over your on-demand costs;
recommendationText=Consider virtual machine reserved instance to save over your on-demand costs;
recommendationTypeId=xxx; instanceName=xxxx;
additionalInfo=;
tags=;
ResourceId=/subscriptions/xxxx/providers/Microsoft.Advisor/recommendations/xxxx}
在这里,我想访问一个字段‘avingsCurrency’,以便在if语句中进行比较.该字段嵌套在‘addtionalInfo’中,而后者又嵌套在‘visorRecommendation’对象中.
我现在有以下代码:
Write-Output "advisorrecommendation: $advisorRecommendation"
if (-not([string]::IsNullOrEmpty($advisorRecommendation.additionalInfo)))
{
$additionalInfo = $advisorRecommendation.additionalInfo | ConvertTo-Json
Write-Output "additionalInfo: $additionalInfo"
if (-not([string]::IsNullOrEmpty($additionalInfo.savingsCurrency)))
{
$savingsCurrency = $additionalInfo.savingsCurrency | ConvertTo-Json
Write-Output "Currency: $savingsCurrency"
}
}
else
{
$additionalInfo = $null
}
此代码给出以下输出:
advisorrecommendation:
@{id=/subscriptions/xxxx/providers/Microsoft.Advisor/recommendations/xxx; category=Cost; impact=High; impactedArea=Microsoft.Subscriptions/subscriptions; description=Consider virtual machine reserved instance to save over your on-demand costs; recommendationText=Consider virtual machine reserved instance to save over your on-demand costs; recommendationTypeId=xxxx; instanceName=xxxx; additionalInfo=; tags=; ResourceId=/subscriptions/xxxx/providers/Microsoft.Advisor/recommendations/xxxx}
additionalInfo: {
"annualSavingsAmount": "697",
"reservedResourceType": "virtualmachines",
"targetResourceCount": "4",
"savingsCurrency": "USD",
"savingsAmount": "58",
"lookbackPeriod": "30",
"displaySKU": "Standard_B2s",
"displayQty": "4",
"location": "westeurope",
"region": "westeurope",
"vmSize": "Standard_B2s",
"subId": "xxxx",
"scope": "Single",
"term": "P1Y",
"qty": "4",
"sku": "Standard_B2s"
}
尽管我可以清楚地看到‘addtionalInfo’中的字段不是空的或空的,但‘avingsCurrency’字段从不通过NULL/Empty判断.这里出了什么问题?如果我不使用前面的存在性判断来try 打印,它只会打印附加了.avingsCurrency的添加信息对象,如下所示:
savingsCurrency: {
"annualSavingsAmount": "697",
"reservedResourceType": "virtualmachines",
"targetResourceCount": "4",
"savingsCurrency": "USD",
"savingsAmount": "58",
"lookbackPeriod": "30",
"displaySKU": "Standard_B2s",
"displayQty": "4",
"location": "westeurope",
"region": "westeurope",
"vmSize": "Standard_B2s",
"subId": "xxxx",
"scope": "Single",
"term": "P1Y",
"qty": "4",
"sku": "Standard_B2s"
}.savingsCurrency