首页 > 解决方案 > 如何使用 PowerShell 获取 Azure 订阅的 TAG 值

问题描述

我可以在 Azure 门户中为我的各种 Azure 订阅分配和查看“标签”值。
但是,当我使用 PowerShell 查询这些订阅时,我找不到与“标签”相关的属性。这似乎很奇怪,因为“标签”被列为所有 PowerShell ResourceGroup 对象的属性,并且资源本身也具有“标签”属性。
如果我可以通过 Azure 门户分配和查看“标签”,为什么我不能在订阅级别查询它们?一定有办法的。

标签: azurepowershelltagssubscription

解决方案


您可以使用 Get-AzTag 获取标签。订阅的 ResourceId 是 /subscriptions/<subscriptionId>

将以下中的 <subscriptionName> 替换为您的订阅名称

$subscription = Get-Subscription -SubscriptionName <subscriptionName>
$tags = Get-AzTag -ResourceId /subscriptions/$subscription

示例: 标签输出示例

您通过以下方式获取标签的值

$tags.Properties.TagsProperty['<TagKey>']

获取标签值示例:当key已知时获取标签值

如果你想遍历标签,你可以做这样的事情

foreach($tagKey in $tags.Properties.TagsProperty.Keys) {
  # $tagKey contains the tag key
  $tagValue = $tags.Properties.TagsProperty[$tagKey]
  Write-Host "$($tagKey):$($tagValue)"
}

示例脚本:


param (
    [Parameter(Mandatory = $false)]
    [string] $SubscriptionName,

    [Parameter(Mandatory = $false)]
    [PSCredential] $Credential
)

if ($Credential) {
    [void] (Connect-AzAccount -Credential $Credential)
}
else {
    [void] (Connect-AzAccount)
}

$subscription = Get-AzSubscription -SubscriptionName $SubscriptionName
if (!$subscription) {
    Write-Output "No subscription named '$($SubscriptionName) was found'"
    exit
}

$tags = Get-AzTag -ResourceId /subscriptions/$subscription

foreach($tagKey in $tags.Properties.TagsProperty.Keys) {
    $tagValue = $tags.Properties.TagsProperty[$tagKey]
    Write-Host "$($tagKey):$($tagValue)"
}

推荐阅读