gpt4 book ai didi

azure - 用于从所有资源组获取标签信息的Powershell脚本

转载 作者:行者123 更新时间:2023-12-02 08:11:07 26 4
gpt4 key购买 nike

我需要检索与租户中所有订阅的所有资源组关联的“所有者”标签。我似乎得到了租户中不存在的记录。也许我的做法是错误的,但我想我应该遍历所有订阅,然后遍历所有资源组,然后遍历标签信息。对于大多数这些资源组,我获得了相同的记录。谁能发现问题吗?

# Connect-AzAccount
$subs = Get-AzSubscription
$count = 1
foreach ($sub in $subs) {
Set-AzContext -SubscriptionId $sub.SubscriptionId
Write-Host $count. $sub.Name
$count ++
$resource_groups = Get-AzResourceGroup
foreach ($rg in $resource_groups) {
Write-Host ' ' $rg.ResourceGroupName
$rgTags = Get-AzTag -Name 'owner'
if ($rgTags -ne $null) {
foreach ($tag in $rgTags.Values) {
Write-Host ' '$tag.Name
}
}
}
}

最佳答案

我建议使用Search-AzGraph查询Resource Manager API ,使用 KQL 比使用单个 cmdlet 更容易、更快捷。

查询可以理解为:

For each container in resourcecontainers where their type is microsoft.resources/subscriptions/resourcegroups and their owner Tag is not null or empty project the properties subscriptionId, resourceGroup, ownertag.

Search-AzGraph -Query @'
resourcecontainers
| where type =~ 'microsoft.resources/subscriptions/resourcegroups'
| extend ownertag = tags.owner
| where isnotempty(ownertag)
| project subscriptionId, resourceGroup, ownertag
'@

关于azure - 用于从所有资源组获取标签信息的Powershell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77053487/

26 4 0