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

使用MS Graph PowerShell SDK无法获取Azure AD用户的CustomSecurityAttributes

问题诊断与解决方案

你的代码存在两个核心问题,导致了ToJson方法调用错误和$Attr返回null的情况,以下是具体修正步骤:

1. 错误使用ToJson方法

Get-MgUser返回的是Microsoft Graph PowerShell对象,该对象的ToJson方法需要传入序列化参数,不支持无参调用。且完全不需要通过JSON转换读取自定义安全属性——可以直接访问对象的内置属性。

2. 冗余的用户查询与属性获取

你已经通过$User = Get-MgUser获取了用户对象,无需重复调用Get-MgUser。默认情况下Get-MgUser不会返回customSecurityAttributes属性,需要在首次查询时明确指定包含该属性。

修正后的完整代码

# Connect to the client(简化逻辑,无需手动处理token)
Function Invoke-Connect-MSGraph($ClientId, $TenantId, $ClientSecret) {
    try {
        Connect-MgGraph -ClientId $ClientId -TenantId $TenantId -ClientSecret $ClientSecret
        Select-MgProfile -Name "beta"
        Write-Host "Connected to MS Graph"
    }
    catch [Exception] {
        Write-Error "Error Connecting. Error was: $($_.Exception.Message)"
        exit
    }
}

# 获取用户并包含自定义安全属性
$EmployeeEmail = "janedoe@xyz.com"
$User = Get-MgUser -Filter "proxyAddresses/any(x:x eq 'smtp:$EmployeeEmail')" -Property "customSecurityAttributes"

# 直接读取自定义安全属性
$AzureCustomSecurityAttributes = $User.CustomSecurityAttributes

# 验证输出
if ($AzureCustomSecurityAttributes) {
    Write-Host "自定义安全属性:"
    $AzureCustomSecurityAttributes | Format-List
} else {
    Write-Host "该用户未配置自定义安全属性"
}

额外注意事项

  • 确保Microsoft Graph PowerShell模块为最新版本,旧版本对beta版属性支持可能存在问题,可执行Update-Module Microsoft.Graph更新。
  • 确认CustomSecAttributeAssignment.ReadWrite.All权限已授予并生效(Azure AD权限授予通常有15-30分钟延迟)。
  • 如果需要更新自定义安全属性,可使用Update-MgUser,示例:
    $updateParams = @{
        CustomSecurityAttributes = @{
            # 替换为你的属性集名称和属性键值
            "YourAttributeSet" = @{
                "YourAttributeKey" = "AttributeValue"
            }
        }
    }
    
    Update-MgUser -UserId $User.Id -BodyParameter $updateParams
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:42:58