Powershell DirectorySearcher Null输出

时间:2016-07-19 17:09:49

标签: powershell active-directory directorysearcher

我正在编写一个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对象似乎只收集它返回的任何记录的“name”值,无论我加载到它中。帮助

1 个答案:

答案 0 :(得分:0)

这样做的时间有点短(与PowerShell v2兼容):

#requires -version 2
param(
  [Parameter(Mandatory=$true)]
    [String] $SearchPattern
)

$searcher = [ADSISearcher] "(&(objectClass=user)(name=$SearchPattern))"
$searcher.PageSize = 1000
$searcher.PropertiesToLoad.AddRange(@("name","samAccountName","userPrincipalName"))
$searchResults = $searcher.FindAll()
if ( $searchResults.Count -gt 0 ) {
  foreach ( $searchResult in $searchResults ) {
    $properties = $searchResult.Properties
    $searchResult | Select-Object `
      @{Name = "name";              Expression = {$properties["name"][0]}},
      @{Name = "sAMAccountName";    Expression = {$properties["samaccountname"][0]}},
      @{Name = "userPrincipalName"; Expression = {$properties["userprincipalname"][0]}}
  }
}
$searchResults.Dispose()

请注意,之后不需要构建列表和输出。只输出每个搜索结果。将此代码放在脚本文件中并调用它:

PS C:\Scripts> .\Searcher.ps1 "*dyer*"

如果省略该参数,PowerShell将提示您(因为参数被标记为必填)。