Solved

Powershell: Search computers in AD

Posted on 2016-08-05
6
54 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 13

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 13

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
Office 365 Advanced Training for Admins

Special Offer:  Buy 1 course, get 2nd free!  Buy the 'Managing Office 365 Identities & Requirements' course w/ Accelerated TestPrep, and automatically receive the 'Enabling Office 365 Services' course FREE!

 
LVL 84

Accepted Solution

by:
oBdA earned 500 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 13

Expert Comment

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

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Active Directory security has been a hot topic of late, and for good reason. With 90% of the world’s organization using this system to manage access to all parts of their IT infrastructure, knowing how to protect against threats and keep vulnerabil…
My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

739 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