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

求编写PowerShell脚本:批量查询OU内计算机信息并填充描述字段

Refined PowerShell Script for AD Computer Inventory & Description Update

Here's an improved version of your script that captures all required fields, handles offline/unreachable machines gracefully, and formats output as requested while updating the AD computer description:

# Define the target OU path
$targetOU = "OU=workstations,OU=workstation,DC=mydomain,DC=local"

# Retrieve all computer accounts from the target OU (include existing description for comparison)
$computers = Get-ADComputer -Filter * -SearchBase $targetOU -Properties Description

# Loop through each computer in the OU
foreach ($computer in $computers) {
    $computerName = $computer.Name
    Write-Host "Processing $computerName..." -ForegroundColor Cyan

    # Initialize all fields with default values to ensure complete output
    $systemVendor = "N/A"
    $systemModel = "N/A"
    $serialNumber = "N/A"
    $currentUser = "N/A"
    $userDisplayName = "N/A"
    $ipv4Address = "N/A"

    # Check if the computer is reachable before attempting remote calls
    if (Test-Connection -ComputerName $computerName -Count 1 -Quiet -ErrorAction SilentlyContinue) {
        try {
            # Fetch hardware details in a single call (optimized instead of three separate WMI calls)
            $systemProduct = Get-CimInstance -ComputerName $computerName -ClassName Win32_ComputerSystemProduct -ErrorAction Stop
            $systemVendor = $systemProduct.Vendor
            $systemModel = $systemProduct.Name
            $serialNumber = $systemProduct.IdentifyingNumber

            # Get current logged-on user (if machine is in use)
            $computerSystem = Get-CimInstance -ComputerName $computerName -ClassName Win32_ComputerSystem -ErrorAction Stop
            if ($computerSystem.UserName) {
                $currentUser = $computerSystem.UserName
                # Fetch user's display name from Active Directory
                try {
                    $adUser = Get-ADUser -Identity $currentUser.Split("\")[1] -Properties DisplayName -ErrorAction Stop
                    $userDisplayName = $adUser.DisplayName
                }
                catch {
                    $userDisplayName = "User not found in AD"
                }
            }

            # Get active IPv4 address (skip IPv6 and loopback addresses)
            $networkConfig = Get-CimInstance -ComputerName $computerName -ClassName Win32_NetworkAdapterConfiguration -ErrorAction Stop | 
                             Where-Object { $_.IPEnabled -eq $true -and $_.IPAddress -ne $null }
            if ($networkConfig) {
                $ipv4Address = $networkConfig.IPAddress | Where-Object { $_ -notmatch ":" } | Select-Object -First 1
                $ipv4Address = $ipv4Address ?? "No IPv4 address found"
            }
        }
        catch {
            Write-Warning "Failed to retrieve data from $computerName : $_"
        }
    }
    else {
        Write-Warning "$computerName is offline or unreachable"
    }

    # Build the formatted string matching your required output structure
    $descriptionString = "$currentUser | $userDisplayName | $ipv4Address | $systemModel | $serialNumber"

    # Update AD description only if it has changed (avoids unnecessary AD writes)
    if ($computer.Description -ne $descriptionString) {
        try {
            Set-ADComputer -Identity $computer -Description $descriptionString -ErrorAction Stop
            Write-Host "Updated description for $computerName successfully" -ForegroundColor Green
        }
        catch {
            Write-Error "Failed to update description for $computerName : $_"
        }
    }
    else {
        Write-Host "Description for $computerName is already up-to-date" -ForegroundColor Gray
    }

    # Print the final formatted result for manual review
    Write-Host "Result: $descriptionString`n" -ForegroundColor White
}

Key Improvements & Explanations:

  • Reachability Check: Uses Test-Connection to skip offline machines, reducing timeouts and unnecessary errors.
  • Modern CIM Calls: Replaced Get-WMIObject with Get-CimInstance (faster, more reliable, and compatible with newer PowerShell versions).
  • Error Handling: try/catch blocks gracefully handle remote access issues and missing AD user records, providing clear feedback.
  • Field Fallbacks: All fields start with "N/A" to ensure the formatted string is complete even if data is unavailable.
  • Efficient Data Fetch: Hardware details are retrieved in one call instead of three, optimizing performance.
  • Targeted IP Address: Filters for active IPv4 addresses only, ignoring irrelevant IPv6 and loopback entries.
  • Conditional Updates: Only modifies the AD description if it differs from the new formatted string, reducing AD traffic.
  • Clear Console Output: Colored text makes it easy to track progress, successes, and warnings at a glance.

Notes:

  • Run this script with Active Directory administrative privileges to modify computer descriptions.
  • For offline machines, fields requiring remote access will remain "N/A" until the machine is reachable.
  • If you need to use Get-WMIObject instead of Get-CimInstance, replace all instances of Get-CimInstance with Get-WMIObject (though Get-CimInstance is recommended for PowerShell 5.1+).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:17:36