PowerShell Script to Get Computer Objects from AD
Get-ADComputer -Filter * to retrieve all computer objects from Active Directory.Examples
How to Think About It
Algorithm
Code
Import-Module ActiveDirectory
$computers = Get-ADComputer -Filter * -Properties Name,OperatingSystem
foreach ($computer in $computers) {
Write-Output "$($computer.Name) - $($computer.OperatingSystem)"
}Dry Run
Let's trace getting all computer objects and printing their names and OS.
Import Active Directory module
Module ActiveDirectory loaded.
Get all computer objects
Retrieve list: COMPUTER1, SRV01, PC01 with their OS properties.
Print each computer's name and OS
Output lines: 'COMPUTER1 - Windows 10 Pro', 'SRV01 - Windows Server 2019', 'PC01 - Windows 11 Enterprise'
| Computer Name | Operating System |
|---|---|
| COMPUTER1 | Windows 10 Pro |
| SRV01 | Windows Server 2019 |
| PC01 | Windows 11 Enterprise |
Why This Works
Step 1: Import Active Directory Module
The Import-Module ActiveDirectory command loads the tools needed to query AD.
Step 2: Get Computer Objects
The Get-ADComputer -Filter * command fetches all computer objects from AD.
Step 3: Display Results
Looping through each computer object, we print its Name and OperatingSystem properties.
Alternative Approaches
Get-ADComputer -LDAPFilter "(objectClass=computer)" -Properties Name,OperatingSystem | ForEach-Object { Write-Output "$($_.Name) - $($_.OperatingSystem)" }
Get-ADComputer -Filter "Name -like 'SRV*'" -Properties Name | ForEach-Object { Write-Output $_.Name }Complexity: O(n) time, O(n) space
Time Complexity
The command queries all computer objects, so time grows linearly with the number of computers in AD.
Space Complexity
Results are stored in memory, so space grows linearly with the number of returned objects.
Which Approach is Fastest?
Using -Filter is generally faster and more readable than -LDAPFilter, but LDAP filters offer more complex querying.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Get-ADComputer -Filter | O(n) | O(n) | Simple and readable queries |
| Get-ADComputer -LDAPFilter | O(n) | O(n) | Complex LDAP queries |
| Filtered by Name Pattern | O(m) | O(m) | Targeted queries with fewer results |
Import-Module ActiveDirectory.Get-ADComputer to be unrecognized.