如何用PowerShell按行输出AD用户直接下属的显示名?
解决AD用户直接下属显示名的表格展示问题
实现思路
要将DirectReports返回的distinguishedName转换为显示名,需遍历每个下属的标识,单独查询AD获取对应显示名,最终输出为规整的表格格式。
完整代码
# 指定目标AD用户的标识(支持用户名、SID或distinguishedName) $user = "目标用户名" # 获取目标用户的直接下属DN列表,逐个查询显示名并整理数据 $directReports = Get-ADUser -Identity $user -Properties DirectReports | Select-Object -ExpandProperty DirectReports $reportData = foreach ($dn in $directReports) { [PSCustomObject]@{ "下属显示名" = (Get-ADUser -Identity $dn).Name } } # 以自适应列宽的表格形式输出结果 $reportData | Format-Table -AutoSize
代码说明
- 先通过
Get-ADUser提取目标用户的DirectReports属性,得到所有下属的distinguishedName列表 - 遍历每个DN,调用
Get-ADUser查询对应的显示名,封装为自定义对象统一格式 - 用
Format-Table -AutoSize输出整齐的表格,自动适配内容宽度
简洁管道写法
如果偏好管道式代码风格,可使用单行简化版:
Get-ADUser -Identity "目标用户名" -Properties DirectReports | Select-Object -ExpandProperty DirectReports | ForEach-Object { [PSCustomObject]@{ "下属显示名" = (Get-ADUser $_).Name } } | Format-Table -AutoSize
内容的提问来源于stack exchange,提问作者PixPaw
相关产品推荐
相关产品推荐

