F.S*_*.S. 3 tags powershell azure subscription
我可以在 Azure 门户中为我的各种 Azure 订阅分配和查看“标签”值。
但是,当我使用 PowerShell 查询这些订阅时,我找不到与“标签”相关的属性。这看起来相当奇怪,因为“标签”被列为所有 PowerShell ResourceGroup 对象的属性,并且资源本身也有一个“标签”属性。
如果我可以通过 Azure 门户分配和查看“标签”,为什么我无法在订阅级别查询“标签”?一定有办法的。
您可以使用 Get-AzTag 获取标签。订阅的 ResourceId 为 /subscriptions/<subscriptionId>
将下面的 <subscriptionName> 替换为您的订阅名称
$subscription = Get-Subscription -SubscriptionName <subscriptionName>
$tags = Get-AzTag -ResourceId /subscriptions/$subscription
Run Code Online (Sandbox Code Playgroud)
示例: 标签输出示例
您可以通过以下方式获取标签的值
$tags.Properties.TagsProperty['<TagKey>']
Run Code Online (Sandbox Code Playgroud)
获取标签值的示例:已知key时获取标签值
如果你想遍历标签,你可以这样做
foreach($tagKey in $tags.Properties.TagsProperty.Keys) {
# $tagKey contains the tag key
$tagValue = $tags.Properties.TagsProperty[$tagKey]
Write-Host "$($tagKey):$($tagValue)"
}
Run Code Online (Sandbox Code Playgroud)
示例脚本:
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)"
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6890 次 |
最近记录: |