求编写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-Connectionto skip offline machines, reducing timeouts and unnecessary errors. - Modern CIM Calls: Replaced
Get-WMIObjectwithGet-CimInstance(faster, more reliable, and compatible with newer PowerShell versions). - Error Handling:
try/catchblocks 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-WMIObjectinstead ofGet-CimInstance, replace all instances ofGet-CimInstancewithGet-WMIObject(thoughGet-CimInstanceis recommended for PowerShell 5.1+).
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

