无法从数组中删除项目

时间:2015-05-21 18:26:26

标签: .net arrays powershell

我正在尝试从数组中删除项目,但无论使用何种方法,它似乎都不起作用。我需要一些帮助来解决这里发生的事情。

我通常默认使用System.Array,但这不起作用,我now understand why

[array]$arrADComputers = Get-ADComputer -Filter 'OperatingSystem -like "Windows 7 Enterprise" ' -Properties Name | select name
$arrADComputers.GetType()
$arrADComputers.count
$arrADComputers.Remove("Machine")
$arrADComputers.count

所以我反而尝试使用System.Collections.ObjectModel.Collection,但这也不起作用。

$Collection1 = {$arrADComputers}.Invoke()
$Collection1.GetType()
$Collection1.Count
$Collection1.Remove("Machine")
$Collection1.count

System.Collections.ArrayList

也是如此
[System.Collections.ArrayList]$Collection2 = $arrADComputers
$Collection2.GetType()
$Collection2.Count
$Collection2.Remove("Machine")
$Collection2.count

但如果我像这样创建一个数组,它可以正常工作:

[System.Collections.ArrayList]$Trash1 = 1,"this",2,"that",3,"them","4"
$Trash1.GetType()
$Trash1.Count
$Trash1.Remove("that")
$Trash1.Count

$TrashTmp = 1,"this",2,"that",3,"them","4"
$Trash2 = {$TrashTmp}.Invoke()
$Trash2.GetType()
$Trash2.Count
$Trash2.Remove("that")
$Trash2.Count

我不理解什么概念阻止我从数组中删除项目?

2 个答案:

答案 0 :(得分:3)

Get-ADComputer的返回类型为[Microsoft.ActiveDirectory.Management.ADComputer],而不是[String],因此您无法通过提供名称来移除计算机。

如果名称属性匹配,您可以迭代整个集合并将其删除,但您最好先使用Where-Object或使用-Filter Get-ADComputer参数进行过滤。< / p>

如果您关心的只是计算机名称,那么请仅使用名称制作arraylist:

$Collection = [System.Collections.ArrayList](Get-ADComputer -Filter * | Select-Object -ExpandProperty Name)
$Collection.Remove('ComputerName')

这应该有效,因为现在arraylist是所有字符串(只是名称)。

答案 1 :(得分:2)

@briantist在这里给出了实际的问题,即你没有一个字符串数组,你有一个ADComputer对象数组。因此,当您尝试删除字符串“machine”时,它无法找到它。对此有点不好的解决方法是重建除目标对象之外的数组,以便删除那个ADComputer对象。像这样:

[array]$arrADComputers = Get-ADComputer -Filter 'OperatingSystem -like "Windows 7 Enterprise" ' -Properties Name | select name
$arrADComputers.GetType()
$arrADComputers.count
$arrADComputers = $arrADComputers | Where{$_.samaccountname -ne "machine"}
$arrADComputers.count

或者,您可以找到要删除的对象,然后像以前一样使用Remove()方法,例如:

[array]$arrADComputers = Get-ADComputer -Filter 'OperatingSystem -like "Windows 7 Enterprise" ' -Properties Name | select name
$arrADComputers.GetType()
$arrADComputers.count
$objComputer = $arrADComputers | Where{$_.samaccountname -eq "machine"}
$arrADComputers.Remove($objComputer)
$arrADComputers.count