[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Powershell: Search computers in AD

Posted on 2016-08-05
6
Medium Priority
?
62 Views
Last Modified: 2016-08-30
Hello Experts,

I need assistance with a query that would search the computer object in the forest, and return the dnshostname of the computer object. I have a file with 100+ computer names. There are about 10 domains in the forest, and the computer object could be in any of the domains. The following line only looks at the domain I am logged in.

Get-ADComputer <computer name> | select dnshostname

Thanks much for your help.
0
Comment
Question by:Parity123
  • 3
  • 2
6 Comments
 
LVL 14

Expert Comment

by:Dustin Saunders
ID: 41745156
You can use -Server to connect to any other DC and grab info from that domain.

$computers = Get-ADComputer -Filter * -Server $domainDC

Open in new window


Then just drop the computers into an array or datatable for each domain and you're all set.
0
 

Author Comment

by:Parity123
ID: 41745458
I don't know which domain the computer belongs to.  I want to query AD for the computers and return the dnshostname. There are a few hundred thousand computer objects, putting them in an array will not work, and is very tedious.
0
 
LVL 14

Expert Comment

by:Dustin Saunders
ID: 41745506
That's not correct- if you are going to be looking for an object(s) across multiple domains you need to put the info into array or data table, otherwise looking for 100 computers will take an hour instead of 30 seconds because you requery each domain each time (SLOW!). You want to collect the information ONCE and then look through it in memory.

If you want a more specific answer you need to provide more specific information about your environment domain/forest setup.
0
 The Evil-ution of Network Security Threats

What are the hacks that forever changed the security industry? To answer that question, we created an exciting new eBook that takes you on a trip through hacking history. It explores the top hacks from the 80s to 2010s, why they mattered, and how the security industry responded.

 
LVL 85

Accepted Solution

by:
oBdA earned 2000 total points (awarded by participants)
ID: 41747499
This will create one single ldap query for all computer names per domain at once, then build the result list.
Tested this with a list of 200 machines, though not in a domain with "a few hundred thousand" computers; I have no idea if this will bring your AD to a grinding halt (though it shouldn't; it's cheaper than querying the domain 100 times for a single computer, and it's cheaper as well than querying for all few hundred thousand computers at once).
Default is to query all domains in the forest, or you can pass your own array of domains using the -Domains argument.
The computer list is expected as a string array as well; you can obviously change the default path to your likings.
If you pass the -QueryCredentials switch, you'll be prompted for credentials for each domain; if you don't pass any for a domain, the logged on user will be used for this domain.
Finally, if you pass a path to the -ExportCsv argument, the results will be exported to a csv, otherwise passed down the pipeline, where you can process the output at will.
[CmdletBinding()]
Param(
	[string[]]$Domains = $(Get-ADForest | Select-Object -ExpandProperty Domains),
	[string[]]$ComputerList = $(Get-Content -Path "C:\Temp\servers.txt"),
	[switch]$QueryCredentials,
	[string]$ExportCsv
)
$Filter = '(|(cn=' + ($ComputerList -join ')(cn=') + '))'
$ADComputerTable = New-Object -TypeName System.Data.Datatable
ForEach ($Column In ('Domain', 'ComputerName', 'DNSHostName')) {
	[void]$ADComputerTable.Columns.Add($Column)
}
$Credentials = @{}
ForEach ($Domain In $Domains) {
	$Credentials[$Domain] = @{}
	If ($QueryCredentials -and ($Credential = Get-Credential -Message "Logon information for $($Domain):" -UserName "$($Domain)\Administrator")) {
		$Credentials[$Domain]['Credential'] = $Credential
	}
}
ForEach ($Domain In $Domains) {
	Try {
		$Credential = $Credentials[$Domain]
		"Querying domain '$($Domain)' using '$($Credential['Credential'].UserName)' ... " | Write-Host -ForegroundColor White -NoNewline
		Get-ADComputer -LDAPFilter $Filter -Server $Domain @Credential -ErrorAction Stop | ForEach-Object {
			[void]$ADComputerTable.Rows.Add($Domain, $_.Name, $_.DNSHostName)
		}
		'OK' | Write-Host -ForegroundColor Green
	} Catch {
		$_.Exception.Message | Write-Host -ForegroundColor Red
		Exit 1
	}
}
$Results = ForEach ($ComputerName In $ComputerList) {
	"Looking for '$($ComputerName)' ... " | Write-Host -ForegroundColor White -NoNewline
	$Result = $ComputerName | Select-Object -Property @{n='ComputerName'; e={$_}}, DNSHostName, Exception
	$ADComputer = $ADComputerTable.Select("ComputerName='$($ComputerName)'")
	Switch ($ADComputer.Count) {
		0 {$Result.Exception = 'NOT FOUND'}
		1 {$Result.DNSHostName = $ADComputer.DNSHostName}
		Default {$Result.Exception = "MULTIPLE RESULTS: $($ADComputer.DNSHostName -join ', ')"}
	}
	If ($Result.Exception) {$Result.Exception | Write-Host -ForegroundColor Red} Else {$Result.DNSHostName | Write-Host -ForegroundColor Green}
	$Result
}
If ($ExportCsv) {
	$Results | Export-Csv -Path $ExportCsv -NoTypeInformation
	"`r`nDone - results written to '$ExportCsv'" | Write-Host -ForegroundColor Yellow
} Else {
	$Results
}

Open in new window

0
 

Author Comment

by:Parity123
ID: 41752437
Thank you so much
0
 
LVL 14

Expert Comment

by:Dustin Saunders
ID: 41776008
The asker seemed to have gotten an acceptable answer from oBdA.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Active Directory can easily get cluttered with unused service, user and computer accounts. In this article, I will show you the way I like to implement ADCleanup..
It’s time for spooky stories and consuming way too much sugar, including the many treats we’ve whipped for you in the world of tech. Check it out!
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Loops Section Overview

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question