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

如何编写脚本实现输入服务器名搜索文本存储的AD域列表查找孤立Windows服务器

跨多域查询AD孤立Windows服务器实现方案

前置依赖

  • 运行设备需安装Active Directory模块(属于RSAT工具集)
  • 所有待查询域名按每行1个的格式存入domains.txt,和脚本放置在同一路径
  • 运行脚本的账号需拥有所有待查询域的AD读取权限

完整PowerShell脚本

# 导入AD管理模块
Import-Module ActiveDirectory -ErrorAction Stop

# 读取域列表文件
try {
    $domainList = Get-Content -Path ".\domains.txt" | Where-Object { $_ -notmatch '^\s*$' }
}
catch {
    Write-Error "读取domains.txt文件失败,请检查文件是否存在"
    exit 1
}

# 获取用户输入的目标服务器名
$targetServer = Read-Host "请输入需要查询的服务器名称"

$matchDomains = @()

# 遍历所有域执行查询
foreach ($domain in $domainList) {
    $domain = $domain.Trim()
    try {
        $queryResult = Get-ADComputer -Filter "Name -eq '$targetServer'" -Server $domain -ErrorAction Stop
        if ($queryResult) {
            $matchDomains += $domain
        }
    }
    catch {
        Write-Warning "查询域 $domain 失败,跳过该域:$($_.Exception.Message)"
        continue
    }
}

# 输出最终结果
if ($matchDomains.Count -gt 0) {
    Write-Host "查询完成,服务器 $targetServer 存在于以下域:"
    $matchDomains | ForEach-Object { Write-Host "- $_" }
}
else {
    Write-Host "*查询完成,服务器 $targetServer 未在所有待查域中找到,属于孤立服务器*"
}

使用注意事项

  • 运行脚本前请先测试单域查询是否正常,确认账号权限和网络连通性无问题
  • 若运行时提示找不到Active Directory模块:
    • 桌面端Windows 10/11:进入「设置-应用-可选功能-添加功能」,安装「RSAT: Active Directory 域服务和轻型目录服务工具」
    • Windows Server:通过服务器管理器的「添加角色和功能」向导,安装「AD域服务工具」功能
  • domains.txt请勿包含多余空行、空格,避免查询失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:15:03