【发布时间】:2017-10-20 06:37:15
【问题描述】:
我的以下脚本正在成功运行。但它不会读取不区分大小写的标签字段。
$resources = Get-AzureRmResource | Where-Object {($_.ResourceType -eq "Microsoft.Compute/virtualMachines") -or ($_.ResourceType -eq "Microsoft.Sql/servers/databases")} |
foreach {
new-object -TypeName psobject -Property @{
ResourceName = $_.ResourceName;
ResourceType = $_.ResourceType;
OperatingHours =
if ( ($_ | select -expand Tags).OperatingHours -ieq $null )
{"TAG NOT PRESENT"}
elseif ( ($_ | select -expand Tags).OperatingHours -ieq '')
{"NULL/EMPTY"}
else
{($_ | select -expand Tags).OperatingHours} ;
}
}
$resources | Format-Table
上述脚本的输出是:
ResourceType ResourceName OperatingHours
------------------------ -------------- ------------------
Microsoft.Compute/virtualMachines asa-perfvm16 TAG NOT PRESENT
Microsoft.Compute/virtualMachines OAASLogicApps1 TAG NOT PRESENT
Microsoft.Compute/virtualMachines VMForPerfTest TAG NOT PRESENT
这里,一些资源没有“OperatingHours”,而是有“operatinghours”或“Operatinghours”或任何其他案例组合。该值由用户设置,因此可以是任意大小写组合。 我上面的脚本没有获取与 Tags.Key 不区分大小写相关的正确数据。我不关心 Tags.Value 的情况。
我尝试使用以下方法修改上述脚本,但输出仍然相同。输出中出现的三个资源列表;所有资源都是由我创建的,所以我确信所有资源中都存在相关标签,但情况不同。
修改后的脚本(但没有成功):
$resources = Get-AzureRmResource | Where-Object {($_.ResourceType -eq "Microsoft.Compute/virtualMachines") -or ($_.ResourceType -eq "Microsoft.Sql/servers/databases")} |
foreach {
$rTags = @{}
foreach($key in $resources.Tags.key)
{
$rTags.Add($key.ToLower(), $resources.Tags[$key].ToLower())
}
new-object -TypeName psobject -Property @{
ResourceName = $_.ResourceName;
ResourceType = $_.ResourceType;
OperatingHours =
if ( $rTags.OperatingHours -ieq $null )
{"TAG NOT PRESENT"}
elseif ( $rTags.OperatingHours -ieq '')
{"NULL/EMPTY"}
else
{$rTags.OperatingHours} ;
}
}
$resources | Format-Table
我哪里错了?
【问题讨论】:
-
我认为您的问题与
OperatingHours属性名称的区分大小写无关。 PowerShell 将变量名称处理为不区分大小写 -> 检查此链接:msdn.microsoft.com/en-us/powershell/reference/5.1/…。如果您将属性存在的检查更改为:[bool]($TestObject.PsObject.Properties.name -match "PropertyNameToCheck"),也许会有所帮助。
标签: powershell azure scripting azure-powershell