简体   繁体   中英

piping ADSI output into another powershell script for finding domain computers

I have moved to a company that has legacy servers and no RSAT so I cannot use AD module and have to make sure the script is v2 compliant.

I have written a discovery script to find all the domains in the forest and I am trying to pipe it into another script to findout all the dns hostnames of the computers in the domains that I have access too but keep getting various errors.

Domains In Forest Code:

$Root = [ADSI]"LDAP://RootDSE"
$oForestConfig = $Root.Get("configurationNamingContext")
$oSearchRoot = [ADSI]("LDAP://CN=Partitions," +     $oForestConfig)
$AdSearcher = [adsisearcher]"(&(objectcategory=crossref)    (netbiosname=*))"
$AdSearcher.SearchRoot = $oSearchRoot
$Domains = $AdSearcher.FindAll()
return $Domains|$Domains = "dc=" + $Domains.Name.Replace(".",     ",dc=") |Out-File C:\domains.txt

Code to find dns host names:

$doms = Get-Content C:\domains.txt
foreach ($dom in $doms) {
$AD = (([adsisearcher]"").Searchroot.path)
IF ($AD -notlike "LDAP://*") {$AD ="LDAP://$AD"}
$AD.Filter = "(&(objectCategory=Computer)(name=$item))"
$Computers = $AD.Filter.FindAll()
$ComputerNames = $Computers.Properties.dnshostname
}

Any ideas?

You can use all the .NET classes in PowerShell, which can make things easier here. In fact, [adsi] and [adsisearcher] are "type accelerators" for the DirectoryEntry and DirectorySearcher classes.

For this use case, you can use Forest.GetCurrentForest() to find the forest and read all the domains in the forest. Then, for each domain, find all the computers.

Here is an example of how you would do that. It's probably not going to be formatted the way you want, but you can change that how you want.

$forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

foreach ($domain in $forest.Domains) {
    $domain.Name
    $searcher = [adsisearcher]"(objectCategory=Computer)"
    $searcher.SearchRoot = [adsi]"LDAP://$($domain.Name)"
    $searcher.PropertiesToLoad.Add("dNSHostName") | Out-Null

    foreach ($comp in $searcher.FindAll()) {
        $comp.Properties["dnsHostName"][0]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM