Forum Discussion
robmo
Jan 13, 2023Brass Contributor
Finding computer names in a hashtable
Hi, I need a script that can find a list of computers from Active Directory stored in a hashtable and return the CanonicalName when there is a match. I know how to get all AD computers from domain c...
robmo
Jan 13, 2023Brass Contributor
This code block finds a computer in the hashtable but the CanonicalName value includes the CanonicalName for every computer in Active Directory. So, each computer found has 100s of CanonicalNames equal to each computer that is in the hashtable.
$report = @()
foreach ($computer in $computers) {
foreach($name in $allADComputers.Name) {
if($computer -eq $name) {
$report += New-Object -TypeName PSObject -Property @{"ComputerName" = $computer;"ActiveDirectoryPath" = $allADComputers.CanonicalName}
}
}
}
How do I get this to set the CanonicalName one time for the computer that is found?
RGijsbersRademakers
Jan 14, 2023Iron Contributor
Hi robmo,
With the following statement, you're dumping all CanonicalNames indeed.
$allADComputers.CanonicalName
I think this should do the trick:
$report = @()
foreach ($computer in $computers) {
foreach($comp in $allADComputers) {
if($computer -eq $comp.Name) {
$report += New-Object -TypeName PSObject -Property @{"ComputerName" = $computer;"ActiveDirectoryPath" = $comp.CanonicalName}
}
}
}
In the second foreach loop you'll retrieve the full record and only match on name in the if statement. In the report you can make use of the CanonicalName value for that specific computer entry.
Regards.
Ruud