在Powershell中返回可选列表

时间:2019-03-22 16:40:54

标签: powershell active-directory

我正在编写一个Powershell脚本,它将搜索活动目录并为我提供有关这样的用户的信息:

$fname = Read-Host 'Enter first name'
$lname = Read-Host 'Enter Last Name'
$search = [adsisearcher]"(&(ObjectCategory=Person)(ObjectClass=User)(givenName=$fname)(sn=$lname))"

$users = $search.FindAll()

    foreach($user in $users) {
    $displayname = $user.Properties['displayname']
    "$displayname"
    }

这将返回具有相同名字和姓氏的用户列表:

User1
用户2
用户3
User4

然后,我希望能够选择要向其显示更多信息的用户,如下所示:

Read-Host 'Enter user number'
#input 1 - 4

#returns exchange server name for the selected user:
$msExchHomeServerName = $user.Properties['msExchHomeServerName']
"Exchange server: $msExchHomeServerName" 

我不知道如何返回一个可选择的列表,该列表使我可以获取有关该用户的更多详细信息。

1 个答案:

答案 0 :(得分:0)

这对我有用。我确定我对PSCustomObjects较为熟悉,但是我可以将其作为哈希表来代替(尽管我认为,如果您尝试使用整数作为键,则哈希表会变得很有趣)。

对不起,我懒得用ADSI进行重构,但希望逻辑清楚。

如果需要,可以返回初始LDAP查询可能需要的用户属性,并将它们添加到为每个用户创建的[PSCustomObject]中。然后只需将属性从$usertable中拉出,而不是执行另一个AD查询。 (请参见第二个示例。)

但是,我真的坚信,如果对于多个用户来说,它具有多个属性,请不要尝试立即获取所有内容。当您只想要一个属性时,我真的很讨厌使用-properties *的惰性LDAP过滤器。在我的环境中,如果仅通过我的帐户获得所有属性,则为74 KB。将内容拖出LDAP时,这很快就开始累积起来。

# sort user list by desired attribute below e.g. samaccountname, lastname, etc
$users = get-aduser -filter 'name -like "macdo*"' | sort samaccountname
# create an array to store the user results
$usertable = @()
$no = 0
$users | foreach {
    $no++
    $o = [PSCustomObject]@{
        No     = $no
        Name   = $_.samaccountname
    }
    $usertable += $o
}
$usertable |sort no

# this is what the table will look like on screen 
No Name
-- ----
1  AKMacDonald
2  AMacDonald
3  BMacDonald
4  BMacdonnell

$myint = Read-Host 'Enter user number'
> Enter user number: 29

# Select desired user properties in Get-ADUser below
$ADuser = $usertable | where {$_.no -eq $myin} |select -ExpandProperty Name | 
Get-Aduser -Properties msExchHomeServerName

$ADuser
#AD user output
DistinguishedName : CN=BMacDonald,OU=Accounts,DC=example,DC=com
Enabled           : False
GivenName         : Bruce
Name              : BMacDonald
...

如果您在初始AD查询中获取了一些额外的属性,则可以将它们存储在$usertable中以便快速检索。

# grab msExchHomeServerName in this query
$users = get-aduser -filter 'name -like "macdo*"' -properties msExchHomeServerName | 
sort samaccountname
# create an array to store the user results
$usertable = @()
$no = 0
$users | foreach {
    $no++
    $o = [PSCustomObject]@{
        No     = $no
        Name   = $_.samaccountname
        Exchsrv= $_.msExchHomeServerName
    }
    $usertable += $o
}
# do a "select" below if you don't want to display everything in $usertable
$usertable |sort no
# $usertable contents
No Name        Exchsrv
-- ----        ----
1  AKMacDonald Exch1
2  AMacDonald  Exch1
3  BMacDonald  Exch2
4  BMacdonnell Exch3

$myint = Read-Host 'Enter user number'
> Enter user number: 29

# Select desired user properties from $usertable
$usertable | where {$_.no -eq $myint} | Select Name,Exchsrv

# output
Name        Exchsrv
----        ----
AKMacDonald Exch1