首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell DirectorySearcher空输出

Powershell DirectorySearcher空输出
EN

Stack Overflow用户
提问于 2016-07-20 01:09:49
回答 1查看 1.4K关注 0票数 0

我正在编写一个powershell脚本,用于搜索Active Directory OU中的用户,并允许我通过从列表中选择匹配项来重置密码。我找到了一个使用System.DirectoryServices.DirectoryEntry和System.DirectoryServices.DirectorySearcher的Tutorial,并对其进行了如下修改:

代码语言:javascript
复制
$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

这工作得很好,但是当它打印数据时,我只能得到返回的任何数据的“名字”值。其他的都变成空了,我不知道为什么。

代码语言:javascript
复制
Name Value                             
---- -----                                                
3    {James3 [REDACTED], $null, $null}      
2    {James2 [REDACTED], $null, $null}      
1    {James1 [REDACTED], $null, $null}         

我尝试过不同类型的身份验证和值操作,但是DirectorySearcher对象似乎只收集它返回的任何记录的"name“值,无论我向其中加载什么。帮助?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-20 23:43:11

下面是一种更简短(且与PowerShell v2兼容)的方法:

代码语言:javascript
复制
#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()

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

代码语言:javascript
复制
PS C:\Scripts> .\Searcher.ps1 "*dyer*"

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38464610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档