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

使用PowerShell获取本地同步用户SAM账号名和SID遇问题

解决PowerShell获取Azure AD本地同步用户SAM账户名和SID的问题

问题概述

尝试通过PowerShell获取本地同步至Azure AD的用户的SAM账户名和安全标识符(SID)时遇到两个问题:

  1. 使用Get-AzureADUser并通过onPremisesSyncEnabled eq true过滤时,触发Request_UnsupportedQuery错误,提示onPremisesSyncEnabled属性不存在
  2. 改用Get-AzureADMSUser后,能正常获取用户UPN,但onPremisesSamAccountName和onPremisesSecurityIdentifier字段返回空值

解决方案

原因说明

  • Get-AzureADUser属于AzureAD模块,其OData查询语法不支持通过onPremisesSyncEnabled属性过滤用户,因此会触发查询不支持的错误
  • Get-AzureADMSUser属于Microsoft Graph PowerShell模块,支持onPremisesSyncEnabled过滤,但默认仅返回用户基础属性,必须显式指定需要获取的扩展属性(包括SAM账户名和SID)

正确脚本(Microsoft Graph模块)

# 首次运行需安装模块并授权,后续可跳过
# Install-Module -Name Microsoft.Graph.Users -Scope CurrentUser
# Connect-MgGraph -Scopes "User.Read.All"

# 获取本地同步用户并指定需要的属性
$syncedUsers = Get-AzureADMSUser -Filter "onPremisesSyncEnabled eq true" -Select "UserPrincipalName", "onPremisesSamAccountName", "onPremisesSecurityIdentifier"

# 遍历输出用户信息
foreach ($user in $syncedUsers) {
    Write-Output "用户UPN: $($user.UserPrincipalName)"
    Write-Output "  SAM账户名: $($user.onPremisesSamAccountName)"
    Write-Output "  安全标识符(SID): $($user.onPremisesSecurityIdentifier)"
    Write-Output ""
}

替代方案(AzureAD模块)

如果必须使用AzureAD模块,可以通过判断onPremisesSecurityIdentifier是否存在来筛选同步用户(本地同步用户都会携带该属性):

Connect-AzureAD

$syncedUsers = Get-AzureADUser -All $true | Where-Object { $null -ne $_.onPremisesSecurityIdentifier }

foreach ($user in $syncedUsers) {
    Write-Output "用户UPN: $($user.UserPrincipalName)"
    Write-Output "  SAM账户名: $($user.onPremisesSamAccountName)"
    Write-Output "  安全标识符(SID): $($user.onPremisesSecurityIdentifier)"
    Write-Output ""
}

注意:此方案需要先获取所有用户再过滤,当Azure AD用户量较大时,性能会有所下降。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:54:52