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

如何用PowerShell/Active Directory从CSV/Excel获取设备的DistinguishedName或OU

用PowerShell查询指定计算机列表的AD OU信息

方法一:导入CSV文件查询

如果你的计算机列表保存在CSV文件中,按以下步骤操作:

  1. 准备CSV文件:确保CSV包含一列存储计算机名称,列标题建议设为ComputerName(若用其他标题,脚本中需对应修改),示例格式:

    ComputerName
    PC-Office-01
    LAPTOP-Sales-05
    Server-DB-02
    
  2. 执行PowerShell脚本:

    # 替换为你的CSV文件实际路径
    $computerList = Import-Csv -Path "C:\Data\Computers.csv"
    
    # 循环查询每台计算机的AD信息
    foreach ($item in $computerList) {
        $pcName = $item.ComputerName
        try {
            # 查询AD计算机对象,指定获取DistinguishedName属性(默认不返回该属性)
            $adPC = Get-ADComputer -Identity $pcName -Properties DistinguishedName
            
            # 构造输出对象,包含所需信息
            [PSCustomObject]@{
                ComputerName      = $pcName
                DistinguishedName = $adPC.DistinguishedName
                OUPath            = $adPC.DistinguishedName -replace "^CN=.*?(?=OU=)", "" # 提取纯OU路径
            }
        }
        catch {
            # 处理未找到的计算机,返回提示信息
            [PSCustomObject]@{
                ComputerName      = $pcName
                DistinguishedName = "AD中未找到该计算机"
                OUPath            = "AD中未找到该计算机"
            }
        }
    } | Export-Csv -Path "C:\Data\AD_Computer_Results.csv" -NoTypeInformation
    

方法二:脚本内直接定义计算机列表

如果计算机数量不多,可直接在脚本里列出设备名称:

# 直接定义要查询的计算机名称数组
$computerNames = @(
    "PC-001",
    "LAPTOP-Marketing-03",
    "Server-Files-01"
)

foreach ($pcName in $computerNames) {
    try {
        $adPC = Get-ADComputer -Identity $pcName -Properties DistinguishedName
        [PSCustomObject]@{
            ComputerName      = $pcName
            DistinguishedName = $adPC.DistinguishedName
            OUPath            = $adPC.DistinguishedName -replace "^CN=.*?(?=OU=)", ""
        }
    }
    catch {
        [PSCustomObject]@{
            ComputerName      = $pcName
            DistinguishedName = "AD中未找到该计算机"
            OUPath            = "AD中未找到该计算机"
        }
    }
} | Export-Csv -Path "C:\Data\AD_Computer_Results.csv" -NoTypeInformation

关键注意事项

  • AD模块依赖:运行脚本的机器需安装Active Directory PowerShell模块。Windows Server可通过Install-WindowsFeature RSAT-AD-PowerShell安装;Windows 10/11可在「设置-应用-可选功能」中添加「RSAT: Active Directory Domain Services and Lightweight Directory Tools」。
  • 权限要求:执行脚本的账号需要具备读取AD计算机对象的权限。
  • Excel转CSV:若原始数据在Excel中,先将文件另存为CSV格式再导入PowerShell,避免格式兼容问题。
  • 列名匹配:如果你的CSV列名不是ComputerName,请修改脚本中$item.ComputerName为对应列名(比如$item.Name)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:05:29