【问题标题】:Add users retrieved from a list to another list of users将从列表中检索到的用户添加到另一个用户列表
【发布时间】:2017-09-06 10:34:12
【问题描述】:

目前,我正在使用以下命令获取所有 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 中的用户添加到一个新的用户列表中(这样我就可以按他们的描述对他们进行分组,然后再做一些事情,比如显示他们的姓名、金额……)

我的方法是什么?

【问题讨论】:

    标签: list powershell data-manipulation


    【解决方案1】:

    实现这一目标的多种方法。我可能会使用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
       }
    }
    

    【讨论】:

    • 我正在尝试使用您提出的第二种方式(因为这就是我要实施的方式)。但是在尝试对数组进行操作后,我似乎无法使用用户的属性(例如 $user.Name )?
    • 您能解释一下您在过滤用户后要做什么吗?
    • 我的“最终目标”是列出已在 foreach 中过滤的每个组。这样我就可以操作列表并检索它们的名称等。你会说 PowerShell 不允许我做这些列表操作吗?
    • 你已经在那里了。运行脚本后,您将获得每个组的列表,您可以使用这些列表来检索其名称等。
    • 嗯,这不是我想要的,但还是谢谢
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多