【发布时间】:2022-02-19 00:53:50
【问题描述】:
我正在编写一个 powershell 脚本,用于搜索 Active Directory OU 中的用户,并允许我通过从列表中选择匹配项来重置密码。我找到了一个使用 System.DirectoryServices.DirectoryEntry 和 System.DirectoryServices.DirectorySearcher 的Tutorial,并将其修改如下:
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP:\\[REDACTED]")
##ReadSTDIN
$strSearch = Read-Host -Prompt "Search"
$strCat = "(&(objectCategory=User)(Name=*" + $strSearch + "*))"
## Search Object
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strCat
$objSearcher.SearchScope = "Subtree"
#Load Required Properties into the dynObjLink
$objSearcher.PropertiesToLoad.Add("name")
$objSearcher.PropertiesToLoad.Add("userPrincipalName")
$objSearcher.PropertiesToLoad.Add("SamAccountName")
##Magical Search Function
$colResults = $objSearcher.FindAll()
$colResults.PropertiesLoaded
#for every returned userID add them to a table
ForEach ($objResult in $colResults)
{$a++
$objResult.count
$objItem = $objResult.Properties
$objItem.name
$objItem.userPrincipalName
$results.Add($a, $objItem.name + $objItem.userPrincipalName + $objItem.SamAccountName)
}
#Print Table
$results | Format-Table -AutoSize
这很好用,但是当它打印数据时,我只能得到返回的任何东西的“名字”值。其他所有内容都变为 NULL,我不知道为什么。
Name Value
---- -----
3 {James3 [REDACTED], $null, $null}
2 {James2 [REDACTED], $null, $null}
1 {James1 [REDACTED], $null, $null}
我尝试了不同类型的身份验证和操作值,但 DirectorySearcher 对象似乎只收集它返回的任何记录的“名称”值,无论我加载什么。帮忙?
【问题讨论】:
-
试试
$objResult.Properties['userPrincipalName']而不是$objResult.Properties.userPrincipalName -
请注意,
$searcher.PropertiesToLoad.Add("x")调用会产生输出。我会推荐AddRange代替:$searcher.PropertiesToLoad.AddRange(@("x","y",'z"))- 没有输出,您可以使用一行代码添加多个属性。 -
您还需要
$result.Properties["userPrincipalName"][0]而不仅仅是$result.Properties["userPrincipalName"],因为$result.Properties["x"]返回ResultValuePropertyCollection,而不是String,所以您需要获取它的第一个元素([0])。跨度> -
这是很久以前的事了,但我了解到,由于某种原因,以前版本的 powershell 以使它们区分大小写的方式调用这些对象。我将它们全部设为小写并设法使脚本正常工作。
标签: powershell active-directory directorysearcher