将 ADSI 输出通过管道传输到另一个 powershell 脚本以查找域计算机

piping ADSI output into another powershell script for finding domain computers

我已经搬到一家拥有旧服务器且没有 RSAT 的公司,所以我无法使用 AD 模块并且必须确保脚本符合 v2。

我已经编写了一个发现脚本来查找林中的所有域,我正在尝试将其通过管道传输到另一个脚本中以找出我也可以访问的域中计算机的所有 dns 主机名,但不断获得各种错误。

森林代码中的域:

$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

查找 DNS 主机名的代码:

$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
}

有什么想法吗?

您可以在 PowerShell 中使用所有 .NET 类,这可以使这里的事情变得更容易。事实上,[adsi][adsisearcher]对于DirectoryEntry and DirectorySearcher类是"type accelerators"。

对于此用例,您可以使用Forest.GetCurrentForest() 查找林并读取林中的所有域。然后,对于每个域,找到所有计算机。

这是您将如何执行此操作的示例。它可能不会按照您想要的方式进行格式化,但您可以根据需要进行更改。

$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]
    }
}