我正在尝试编写powershell代码,该代码可以从给定域中检索OU列表以进行进一步处理。我只想要一个纯文本列表(出于各种原因。)我无法在这些机器上安装AD模块。
$tld = "lan"
$domain = "contoso"
$adLogin = "Administrator"
$mainOU = "Workstations"
$dnSuffix = "OU=$mainOU,DC=$domain,DC=$tld"
$computerPrefix = ""
$computerSuffix = ""
$DomainDN = "LDAP://$domain.$tld"
$adDomain = "$domain" + "." + "$tld"
$adAuthName = "$adDomain\$adLogin"
$Credential = Get-Credential -Credential $adAuthName
# There's probably a better way to do this, but the adsi searcher documentation is hard to sift through, and these machines can't install the AD module.
$remoteObject = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList $DomainDN,$($Credential.UserName),$($Credential.GetNetworkCredential().password)
$adObj = ([ADSISearcher]"ObjectClass=OrganizationalUnit")
$adObj.SearchRoot = $remoteObject
$adObj.PropertiesToLoad.AddRange("CanonicalName")
$ouList = $adObj.findall().Properties.canonicalname | Select-String $mainOU | Out-String
$ouList = $ouList.ToString()
$removeText = "$domain" + "." + "$tld" + "/" + "$mainOU"
$ouList = $ouList -replace $removeText
$ouList = $ouList -replace "/"
$ouList = $ouList.Trim()
$ouList = $ouList.Split("`n")
echo $ouList
在目标域内的计算机上运行它会产生以下结果:(这些是用于实验室模拟的虚假OU。)
chips
vinegar
salsa
但是在域外的计算机上运行它不会产生任何效果。 Powershell似乎没有提供任何工具来解决原因。是的,我已经证实我可以从该机器解析contoso.lan。有人有什么建议吗?
答案 0 :(得分:0)
对于我自己的问题,这是一个更优雅的解决方案:
$domain = "contoso"
$tld = "lan"
$adLogin = "Administrator"
$mainOU = "Workstations"
$dnSuffix = "OU=$mainOU,DC=$domain,DC=$tld"
$adDomain = "$domain" + "." + "$tld"
$adAuthName = "$adDomain\$adLogin"
$adCredentials = Get-Credential -Credential $adAuthName
$ldapRootPath = "LDAP://" + "$domain" + "." + "$tld"
$ldapWorkstationPath = "LDAP://" + "$domain" + "." + "$tld" + "/OU=" + "$mainOU" + ",DC=" + "$domain" + ",DC=" + "$tld"
$remoteObject = New-Object System.DirectoryServices.DirectoryEntry("$ldapWorkstationPath",$($adCredentials.UserName),$($adCredentials.GetNetworkCredential().password)) -ErrorAction 'Stop' -ErrorVariable ErrProcessNewObjectCred
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $remoteObject
$objSearcher.Filter = ("(objectCategory=OrganizationalUnit)")
foreach ($item in "name") {$objSearcher.PropertiesToLoad.Add($item) | Out-Null }
$searchResult = $objSearcher.FindAll()
$ouList = foreach ($result in $searchResult) {$objOrganizationalUnit = $result.Properties; $objOrganizationalUnit.name}
虽然搜索主体不同,但我认为我的问题中发布的代码不起作用的原因是因为我的LDAP路径不完整。应该是LDAP://contoso.lan/OU=Workstaions,DC=contoso,DC=lan(我发现的例子只显示你需要LDAP:// dc = contoso,dc = lan,这是错误的,而powershell不是打扰告诉你这是错的,只是假装没有发生任何事情。)
我基于我在某处找到的代码示例,但现在我再也找不到了,否则我会给原作者一些信用。 (具有讽刺意味的是,它是讨论主题的一部分,作者将其抛弃,转而使用AD模块 - 这是我没有的选项。)
我明白为什么他们使用AD模块,因为这个过程看起来很复杂,如果我没弄错的话是基于.net的? (老实说,我不知道.net和什么不是什么之间的区别;我只是按照示例并根据我的需要调整它,因为我不够熟练,无法成为真正的软件开发人员,哈哈。)