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

如何通过PowerShell查询Active Directory仅获取指定父OU中的用户

解决Active Directory PowerShell查询仅返回父OU用户的问题

你的问题出在Get-ADUser默认的搜索范围上——默认参数-SearchScope的值是Subtree,会递归遍历目标OU的所有子OU,所以会把子OU里的用户也查出来。只需要添加-SearchScope OneLevel参数,就能限制查询仅在父OU本身进行,不会包含子OU内容。

另外建议不要用-Properties *,这会返回用户的所有属性,既浪费资源又影响效率,直接指定你后续需要用到的属性即可,比如ExtensionAttribute2、mail、lastlogondate这类。

修改后的代码如下:

$Outputfile = "C:\outputfile.csv"

Get-ADUser -Filter * `
    -SearchBase "OU=[ParentOU],DC=[domain],DC=[domain]" `
    -SearchScope OneLevel `
    -Properties ExtensionAttribute2, mail, lastlogondate | 
Select-Object Surname, GivenName, ExtensionAttribute2, mail, lastlogondate, distinguishedName | 
Export-Csv -Path $OutputFile -NoTypeInformation

关键修改说明:

  • -SearchScope OneLevel:限定仅搜索指定的父OU层级,不深入子OU
  • 明确指定需要的属性:替代-Properties *,减少不必要的数据返回,提升查询性能
  • 添加-NoTypeInformation:避免导出的CSV文件开头出现冗余的类型信息行,让文件格式更规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:23:14