You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取含指定标签资源组中Contributor角色用户的PowerShell脚本求助

问题分析与修正脚本

原脚本的问题

  • 标签大小写不匹配:Azure标签键不区分大小写,但PowerShell的哈希表索引区分大小写,原脚本用applicationname小写索引,可能匹配不到实际的ApplicationName标签。
  • 未获取角色分配:原脚本只输出了资源组名称,没有实现获取Contributor角色用户的核心需求。
  • 文件写入逻辑错误:每次循环用Out-File会覆盖之前的内容,应该用追加模式或者收集所有结果后一次性写入。
  • 无去重处理:没有对重复的用户信息做去重操作。

修正后的完整脚本

$outputFile = "C:\Users\User\Desktop\contributors.txt"
$allContributors = @()

# 获取标签ApplicationName值包含PROD的资源组(匹配标签键大小写)
$resourceGroups = Get-AzResourceGroup | Where-Object {
    $tagKey = $_.Tags.Keys | Where-Object { $_ -eq 'ApplicationName' }
    $tagKey -and $_.Tags[$tagKey] -like "*PROD*"
}

foreach ($rg in $resourceGroups) {
    Write-Host "正在处理资源组: $($rg.ResourceGroupName)"
    Write-Host "------------------------"
    
    # 获取当前资源组下角色名称包含Contributor的用户分配
    $roleAssignments = Get-AzRoleAssignment -ResourceGroupName $rg.ResourceGroupName | 
        Where-Object { $_.RoleDefinitionName -like "*Contributor*" -and $_.ObjectType -eq 'User' }
    
    # 提取用户信息并添加到集合
    foreach ($assignment in $roleAssignments) {
        $contributorInfo = [PSCustomObject]@{
            ResourceGroupName = $rg.ResourceGroupName
            DisplayName       = $assignment.DisplayName
            UserPrincipalName = $assignment.UserPrincipalName
            RoleName          = $assignment.RoleDefinitionName
        }
        $allContributors += $contributorInfo
    }
}

# 按用户主体名去重
$uniqueContributors = $allContributors | Sort-Object -Property UserPrincipalName -Unique

# 将结果写入文件(UTF8编码避免乱码)
$uniqueContributors | Format-Table -AutoSize | Out-File -FilePath $outputFile -Encoding utf8
Write-Host "处理完成,结果已写入: $outputFile"

# 控制台输出去重后的用户列表
Write-Host "`n去重后的Contributor用户列表:"
$uniqueContributors | Select-Object DisplayName, UserPrincipalName -Unique | Format-Table -AutoSize

关键说明

  • 标签匹配优化:先确认存在ApplicationName标签键,再匹配其值包含PROD的资源组,避免索引不存在报错。
  • 角色筛选精准:只保留用户类型的Contributor角色分配,排除服务主体、组等非用户条目。
  • 去重逻辑:通过用户主体名(UserPrincipalName)作为唯一标识去重,确保同一用户只出现一次。
  • 文件写入优化:收集所有结果后一次性写入,避免循环覆盖,同时指定UTF8编码防止中文乱码。

内容的提问来源于stack exchange,提问作者woodyboow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 15:01:06