目前,我使用此命令获取所有Active Directory用户:
$users = Get-AdUser -Filter {(Enabled -eq "True")} -Properties Description
在此之后,我以这种方式对列表做了各种各样的事情:
foreach ($user in $users)
{
if($user.Description -eq "Admin")
{
Write-Host "This is an admin!"
#Here comes the code that adds the admin to a new list
}
if($user.Description -eq "Secretary")
{
Write-Host "This is a Secretary!"
#Here comes the code that adds the secretaries to a new list
}
}
我想要做的是将foreach
中的用户添加到新的用户列表中(因此我可以按照他们的描述对其进行分组,然后执行诸如显示其名称,金额等的事情... )
我的方法是什么?
答案 0 :(得分:2)
实现这一目标的多种方法。我可能会使用Where-Object
cmdlet来过滤它们:
$admins = $users | Where-Object Description -eq 'Admin'
$secretaries = $users | Where-Object Description -eq 'Secretary'
另一种方法是在foreach循环之前初始化数组,并将它们添加到if语句中:
$admins = @()
$secretaries = @()
foreach ($user in $users)
{
if($user.Description -eq "Admin")
{
Write-Host "This is an admin!"
$admin += $user
}
if($user.Description -eq "Secretary")
{
Write-Host "This is a Secretary!"
$secretaries += $user
}
}