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

如何用PowerShell从文本文件批量查询服务器所在OU?

How to Batch Retrieve OU for Servers from a Text File with PowerShell

Got it, let's break this down. I've dealt with exactly this kind of Active Directory lookup task before, so here's a straightforward, reliable way to use a foreach loop to read your server list and pull their OUs from AD—no need for that overly complex TechNet script if it wasn't working for you.

Step 1: Prep Your Server List

First, make sure your text file (let's call it servers.txt) has one server name per line, no extra spaces or empty lines (though we'll handle those just in case). Example:

Server01
Server02
DC01
FileServer01

Step 2: PowerShell Script with Foreach Loop

This script uses native Active Directory cmdlets, is easy to debug, and handles edge cases like missing servers. Here's the full code:

# Load the Active Directory module (required for AD queries)
Import-Module ActiveDirectory

# Update this path to point to your server list file
$serverList = Get-Content -Path "C:\Scripts\servers.txt"

# Loop through each server in the list
foreach ($server in $serverList) {
    # Skip empty lines to avoid errors
    if ([string]::IsNullOrWhiteSpace($server)) {
        continue
    }

    try {
        # Fetch the AD computer object, focusing on the DistinguishedName property
        $adComputer = Get-ADComputer -Identity $server -Properties DistinguishedName -ErrorAction Stop
        
        # Extract the OU path from the DistinguishedName
        # DN format is: CN=ServerName,OU=Department,OU=Location,DC=domain,DC=com
        # Split after the first comma to separate the server name from the OU/domain parts
        $ouPath = ($adComputer.DistinguishedName -split ",", 2)[1]

        # Output the result (you can pipe this to a CSV later if needed)
        [PSCustomObject]@{
            ServerName = $server
            OU_Path    = $ouPath
        }
    }
    catch {
        # Catch and report errors (e.g., server not found in AD)
        Write-Warning "Failed to find server '$server' in AD: $($_.Exception.Message)"
    }
}

Key Details to Note

  • Module Requirement: You'll need the Active Directory PowerShell module installed. This comes pre-installed on domain controllers, or you can install the RSAT (Remote Server Administration Tools) package on a client machine.
  • Permissions: The account running the script needs read access to your Active Directory environment.
  • Export to CSV: If you want to save results to a file instead of just viewing them in the console, add this to the end of the script (pipe the PSCustomObject directly):
    | Export-Csv -Path "C:\Scripts\Server_OU_Results.csv" -NoTypeInformation -Encoding UTF8
    
  • Error Handling: The try/catch block ensures the script keeps running even if some servers aren't found in AD, instead of crashing halfway through.

Why This Works Better Than the TechNet Script

That TechNet script is more generalized, but for your specific use case (batch reading from a text file), this approach is simpler and more transparent. You can easily tweak it to add extra properties or adjust output formats without digging through a complex script.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:16:49