从AD中提取数据后,从阵列中删除数据



我目前正在按组织单位从广告中提取用户数据,然后更新某些字段,这很好。我想修改脚本,只更新某些用户,但很难从数组中删除任何条目,因为它是固定大小的。我转换成了ArrayList,可以得到对象的计数,然后可以单独查询等等

$users = Get-ADUser -Filter * -SearchBase "DN" -Properties GivenName, Surname,mail,UserPrincipalName,SAMAccountName,proxyAddresses | Select GivenName, Surname,mail,UserPrincipalName,SAMAccountName,proxyAddresses 
$WorkingSet =[System.Collections.ArrayList]($users)

$WorkingSet.count给出47作为结果,最后一个元素是:

GivenName:Laura
姓氏:Willox
邮件:WilloxL@domain
用户主体名称:Laura.Willox@domain
SAM帐号名称:Laura。Willox
代理地址:{smtp:laura.willox@domain,SMTP:WilloxL@domain}

但是尝试$WorkingSet.IndexOf('Laura.Willox')会得到-1而不是46所以我不能做像$WorkingSet.RemoveAt($WorkingSet.IndexOf('Laura.Willox'))这样的事情

这个数据是不是有什么我不理解的地方,不能这样查询?

您绝对不需要将数据包装在ArrayList中,这只会使代码不必要地复杂化。

与其尝试在列表中以内联方式修改Get-ADUser的输出,不如使用PowerShell的Where-Objectcmdlet来筛选数据:

$users = Get-ADUser -Filter * -SearchBase "DN" -Properties GivenName, Surname,mail,UserPrincipalName,SAMAccountName,proxyAddresses | Select GivenName, Surname,mail,UserPrincipalName,SAMAccountName,proxyAddresses 
# use `Where-Object` to filter the data based on individual property values
$usersSansLaura = $users |Where-Object SAMAccountName -ne 'Laura.Willox'

这里,我们将$users中包含的任何用户对象管道传输到Where-Object SAMAccountName -ne 'Laura.Willox'——-ne运算符是"0">notequal";运算符,因此输出将是不具有精确值为Laura.WilloxSAMAccountName属性的任何输入对象,然后将这些属性分配给$usersSansLaura

Mathias的有用答案值得考虑:

  • 在PowerShell中,直接操作可调整大小的集合是不常见的
  • 相反,PowerShell中的集合处理通常涉及通过过滤原始集合来创建新的集合,使用管道中的Where-Object,或者对于已经在内存中的集合,使用.Where()数组方法

如果您确实需要就地调整列表数据类型的大小,我建议使用System.Collections.Generic.List`1,它的.FindIndex()方法可以让您执行您想要的操作:

# Note: I'm using [object] as the type parameter for simplicity, but you 
#       could use [Microsoft.ActiveDirectory.Management.ADUser] for strict typing.
$WorkingSet = [System.Collections.Generic.List[object]]::new(
@(Get-ADUser -Filter * -SearchBase "DN" -Properties GivenName, Surname,mail,UserPrincipalName,SAMAccountName,proxyAddresses | Select GivenName, Surname,mail,UserPrincipalName,SAMAccountName,proxyAddresses)
)
# Find the index of the user with a given SAMAccountName: 
$ndx = $WorkingSet.FindIndex({ $args[0].SAMAccountName -eq 'Laura.Willox' })
# If found, remove the user from the list
# (-1 indicates that no matching element was found)
if ($ndx -ne -1) {
$WorkingSet.RemoveAt($ndx)
}

通常,请注意,System.Collections.ArrayListSystem.Collections.Generic.List`1都有一个.Remove()方法,该方法允许您直接传递要移除的对象(元素(,而不管其索引如何。


至于您尝试了什么

由于数组列表由ADUser实例组成,因此.IndexOf()方法需要传递这样的实例以便在元素中定位它-不能只传递引用元素中属性之一的字符串

相反,您需要一个谓词(布尔测试(来将字符串与感兴趣的属性(.SamAccountName(进行比较,这就是上面的.FindIndex()调用所做的。

最新更新