如何使用PowerShell获取Active Directory指定子OU内的所有计算机?
Fixing Your AD Computer Query for the Remote Sites\MyCity\Computers OU
Hey there! Let's get your PowerShell command targeting the right OU and working correctly.
First, the main issue with your current code is that your -SearchBase only points to the MyCity OU, but you need to include the child Computers OU since that's your target location. Also, there's a tiny typo in the property name: it's Enabled (not Enable) for the account status attribute.
Here's the corrected command:
Get-ADComputer -Filter * -SearchBase "OU=Computers,OU=MyCity,OU=Remote Sites,DC=MyDomain,DC=com" | Select-Object -Property Name, DNSHostName, Enabled, LastLogonDate
Quick breakdown of the fixes:
- Updated
-SearchBase: LDAP distinguished names work from the lowest OU up to the domain root. Since your target isRemote Sites\MyCity\Computers, we structure the path asOU=Computers,OU=MyCity,OU=Remote Sites,DC=MyDomain,DC=comto explicitly target that child OU. - Fixed property name:
Enabledis the correct attribute name for checking if a computer account is active in AD. - Formatting: Split the command across lines for readability (PowerShell supports line breaks automatically after a pipe).
Extra tips to make this even better:
- If you're unsure about the exact distinguished name of your target OU, run this command to look it up:
Get-ADOrganizationalUnit -Filter "Name -eq 'Computers'" -SearchBase "OU=MyCity,OU=Remote Sites,DC=MyDomain,DC=com" -Properties DistinguishedName - Add
-SearchScope OneLevelif you only want computers directly in theComputersOU (not any nested sub-OUs under it). The default isSubtree, which includes all nested objects. - Export the results to a CSV for easy review or reporting:
Get-ADComputer -Filter * -SearchBase "OU=Computers,OU=MyCity,OU=Remote Sites,DC=MyDomain,DC=com" | Select-Object -Property Name, DNSHostName, Enabled, LastLogonDate | Export-Csv -Path "C:\Your\Path\MyCity_Computers.csv" -NoTypeInformation
内容的提问来源于stack exchange,提问作者Officer_Narc
相关产品推荐
相关产品推荐

