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

如何使用Active Directory DirectorySearcher查找域内所有运行Windows 10的计算机?

如何使用Active Directory DirectorySearcher查找域内所有运行Windows 10的计算机?

嘿,你的过滤器语法其实已经踩对路子了!LDAP复合过滤器的格式就是用(&())来组合多个条件,你写的(&(objectCategory=computer)(OperatingSystem=Windows 10))本身是符合规范的。不过这里有几个细节能帮你更精准地找到目标计算机,还有一些优化小技巧:

  • 适配操作系统的变体名称
    有些域内的Windows 10计算机,OperatingSystem属性值可能带后缀,比如“Windows 10 Enterprise”、“Windows 10 Pro”或者带版本号。如果只精确匹配“Windows 10”,会漏掉这些机器。建议改用通配符匹配所有Windows 10变体:

    $Searcher.Filter = "(&(objectCategory=computer)(OperatingSystem=Windows 10*))"
    
  • 优化代码逻辑与性能
    你原代码里的SearchRoot设置是没问题的,但可以简化写法,同时建议指定需要加载的属性——默认会返回所有AD属性,既浪费带宽又拖慢速度。比如只加载我们关心的名称、操作系统和DN路径:

    $Searcher.PropertiesToLoad.AddRange(@("name", "operatingSystem", "distinguishedName"))
    

    另外别忘了设置搜索范围,确保遍历整个域的计算机:

    $Searcher.SearchScope = [System.DirectoryServices.SearchScope]::Subtree
    
  • 完整可运行示例
    给你一个更完善的脚本参考,包含凭据处理、结果输出和资源释放:

    # 替换成你的域LDAP路径,比如"LDAP://DC=contoso,DC=com"
    $LDAPProviderPath = "LDAP://DC=yourdomain,DC=com"
    # 可选:如果需要域管理员凭据,填写用户名和密码
    $adminUsername = "yourdomain\adminaccount"
    $adminPassword = "yourpassword"
    
    # 创建AD目录条目
    $searchRoot = New-Object System.DirectoryServices.DirectoryEntry($LDAPProviderPath, $adminUsername, $adminPassword)
    # 初始化搜索器并绑定到目录条目
    $searcher = New-Object System.DirectoryServices.DirectorySearcher($searchRoot)
    
    # 设置过滤条件:匹配所有Windows 10系列操作系统
    $searcher.Filter = "(&(objectCategory=computer)(OperatingSystem=Windows 10*))"
    # 指定要加载的属性,提升查询效率
    $searcher.PropertiesToLoad.AddRange(@("name", "operatingSystem", "distinguishedName"))
    # 设置搜索范围为整个域树
    $searcher.SearchScope = [System.DirectoryServices.SearchScope]::Subtree
    
    # 执行搜索并遍历结果
    try {
        $searchResults = $searcher.FindAll()
        foreach ($result in $searchResults) {
            Write-Host "计算机名称: $($result.Properties["name"][0])"
            Write-Host "操作系统: $($result.Properties["operatingsystem"][0])"
            Write-Host "AD路径: $($result.Properties["distinguishedname"][0])`n"
        }
    }
    finally {
        # 务必释放搜索结果资源,避免内存泄漏
        if ($searchResults) { $searchResults.Dispose() }
    }
    
  • 常见问题排查
    如果没找到预期结果,可以按以下步骤排查:

    • 检查LDAP路径是否正确,比如域名部分是否和你的AD环境匹配
    • 确认使用的凭据有足够权限读取AD中的计算机对象信息
    • 先用(&(objectCategory=computer))作为过滤器,测试是否能获取所有域内计算机,再逐步添加操作系统过滤条件
    • 验证目标Windows 10计算机的OperatingSystem属性是否已经同步到AD中(有些机器可能因为组策略或AD同步问题未更新该属性)

备注:内容来源于stack exchange,提问作者TMOTTM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 14:12:47