Solved

Powershell: Search computers in AD

Posted on 2016-08-05
6
48 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 12

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 12

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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 82

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 12

Expert Comment

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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Deleting Computer From AD Still Lets me Login 1 22
finding who created AD 4 40
last logon 2 14
AD reporting and update tool 9 45
Utilizing an array to gracefully append to a list of EmailAddresses
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…
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 …

707 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now