如何在Get-ADUser查询中仅显示管理员姓名并保留原有属性
解决Get-ADUser查询中Manager字段仅显示姓名的问题
你可以通过修改Select-Object中Manager字段的计算属性,解析LDAP路径并提取管理员姓名,同时保留原有所有查询属性。以下是两种可行的修改方案:
方案1:使用ADSI直接读取(高效无额外AD查询)
这种方法无需额外发起Active Directory查询,直接解析Manager的LDAP路径获取姓名:
Get-ADUser $username -Properties Enabled,employeeNumber,DisplayName,Mail,Description,office,extensionAttribute1,manager,AccountExpirationDate | Select-Object Enabled, @{Expression={$_.DisplayName};Label='Display Name'}, @{Expression={$_.Mail};Label='Email'}, @{Expression={$_.employeeNumber};Label='Employee Number'}, @{Expression={$_.AccountExpirationDate};Label='Account Expiration Date'}, @{Expression={$_.Description};Label='Account Description'}, Office, @{Expression={$_.extensionAttribute1};Label='Cost Center'}, @{Expression={ if ($_.Manager) { # 优先获取DisplayName,若不存在则用Name $managerObj = [ADSI]"LDAP://$($_.Manager)" $managerObj.DisplayName ?? $managerObj.Name } else { '' } };Label='Manager'} | Format-List
方案2:使用Get-ADUser查询Manager对象(适合需要更多属性的场景)
如果需要获取Manager的其他属性,可通过Get-ADUser查询,但会额外发起AD请求:
Get-ADUser $username -Properties Enabled,employeeNumber,DisplayName,Mail,Description,office,extensionAttribute1,manager,AccountExpirationDate | Select-Object Enabled, @{Expression={$_.DisplayName};Label='Display Name'}, @{Expression={$_.Mail};Label='Email'}, @{Expression={$_.employeeNumber};Label='Employee Number'}, @{Expression={$_.AccountExpirationDate};Label='Account Expiration Date'}, @{Expression={$_.Description};Label='Account Description'}, Office, @{Expression={$_.extensionAttribute1};Label='Cost Center'}, @{Expression={ if ($_.Manager) { (Get-ADUser $_.Manager -Properties DisplayName).DisplayName } else { '' } };Label='Manager'} | Format-List
说明
- 两种方案都会保留原有所有查询属性,仅修改Manager字段的输出内容
- 方案1性能更优,适合仅需姓名的场景;方案2灵活性更高,可扩展获取Manager的其他属性
- 添加了空值判断,避免用户无Manager时出现错误
内容的提问来源于stack exchange,提问作者Jamie Lovenduski
相关产品推荐
相关产品推荐

