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

如何在PowerShell中通过哈希表/函数根据订阅ID获取订阅名称

解决方案:替换Azure订阅ID为名称的PowerShell脚本优化

核心问题解决:正确构建订阅哈希表

要实现通过订阅ID快速查询名称,需将哈希表的键设为订阅ID,值设为订阅名称,而非直接用Select-Object返回对象数组。正确的哈希表构建方式:

$subscriptionHash = @{}
Get-AzSubscription | ForEach-Object { $subscriptionHash[$_.Id] = $_.Name }

修改后的完整脚本

以下是优化后的脚本,直接在生成结果对象时填充订阅名称,同时简化对象创建逻辑,优化分组统计:

# Set the output CSV file path
$outputFilePath = "C:\output\Report.csv"

# Create an empty array to store the results
$all_results = @()

# Build subscription hash table: Key = Subscription ID, Value = Subscription Name
$subscriptionHash = @{}
Get-AzSubscription | ForEach-Object { $subscriptionHash[$_.Id] = $_.Name }

# Function to retrieve role assignments for a subscription
function Get-RoleAssignmentsForSubscription {
    param (
        [string]$subscriptionId
    )

    try {   
        $all_results2 = @()
        $roleAssignments = Get-AzRoleAssignment -Scope "/subscriptions/$subscriptionId"
        foreach ($assignment in $roleAssignments) {
            # Filter only User/Group objects to focus on target entities
            if ($assignment.ObjectType -in 'User', 'Group' -and ($null -ne $assignment.DisplayName -or $null -ne $assignment.SignInName)) {
                # Use PSCustomObject for cleaner object creation
                $result_object = [PSCustomObject]@{
                    "Subscription_ID"       = $subscriptionId
                    "Subscription_Name"     = $subscriptionHash[$subscriptionId] ?? "Unknown"
                    "Display Name"          = $assignment.DisplayName
                    "SignIn Name"           = $assignment.SignInName
                    "Object Type"           = $assignment.ObjectType
                    "Object ID"             = $assignment.ObjectId
                    "Role Assignment"       = $assignment.RoleDefinitionName
                    "RoleDefinition ID"     = $assignment.RoleDefinitionId
                    "Scope"                 = $assignment.Scope
                    "Description"           = $assignment.Description
                    "CanDelegate"           = $assignment.CanDelegate
                }
                $all_results2 += $result_object
            }
        }
        return $all_results2
    }
    catch {
        Write-Host "Error retrieving role assignments for subscription $subscriptionId - Error detail: $_"
    }
}

# Get all subscriptions in the Azure account
$subscriptions = Get-AzSubscription

# Loop through each subscription
foreach ($subscription in $subscriptions) {
    $all_results_get_assignment = Get-RoleAssignmentsForSubscription -subscriptionId $subscription.Id
    $all_results += $all_results_get_assignment
}

# Export the results to a CSV file
$all_results | Export-Csv -Path $outputFilePath -NoTypeInformation
Write-Host "Script execution completed. Results exported to $outputFilePath."

# Group by Role Assignment and Subscription Name, sort by count descending
$all_results | Group-Object -Property "Role Assignment", "Subscription_Name" | 
    Select-Object @{Name='Subscription'; Expression={$_.Group[0].Subscription_Name}},
                  @{Name='Role'; Expression={$_.Group[0].'Role Assignment'}},
                  Count | 
    Sort-Object Count -Descending

关键优化点说明

  1. 哈希表高效查询:通过ID直接映射名称,避免重复调用Get-AzSubscription,提升脚本执行效率。
  2. 结果对象简化:用[PSCustomObject]替代New-Object+Add-Member,代码更简洁易维护。
  3. 过滤无关数据:增加ObjectType判断,只保留用户和组的角色分配,减少无效数据。
  4. 友好分组统计:直接使用Subscription_Name字段分组,输出报告显示订阅名称而非ID,提升可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:33:20