[英]Powershell Remove objects from an array list
是否有一种非 for 循环方法可以从 arrayList 中删除某些项目?
$remotesumerrors = $remoteFiles | Select-String -Pattern '^[a-f0-9]{32}( )' -NotMatch
我想从 $remoteFiles var.. 中删除上面的输出..是否有一些管道方法可以删除它们?
假设以下所有情况:
$remotesumerrors
捕获的结果$remoteFiles
是System.IO.FileInfo
实例的集合,例如由Get-ChildItem
输出$remoteFiles
是可以接受的, 您可以使用.Where()
数组方法如下(这优于基于Where-Object
cmdlet 的基于管道的解决方案):
# Get the distinct set of the full paths of the files of origin
# from the Select-String results stored in $remotesumerrors
# as a hash set, which allows efficient lookup.
$errorFilePaths =
[System.Collections.Generic.HashSet[string]] $remotesumerrors.Path
# Get those file-info objects from $remoteFiles
# whose paths aren't in the list of the paths obtained above.
$remoteFiles = $remoteFiles.Where({ -not $errorFilePaths.Contains($_.FullName) })
作为旁白:
[System.Collections.Generic.HashSet[T]]
是获取一组不同值(删除重复项)的快速便捷的方法,但请注意,生成的哈希集的元素总是无序的,并且使用字符串, 默认情况下,查找区分大小写- 有关更多信息,请参阅此答案。使用Where-Object
cmdlet 筛选列表:
$remoteFiles = $remoteFiles |Where-Object { $_ |Select-String -Pattern '^[a-f0-9]{32}( )' -NotMatch }
如果它真的是一个 [collections.arraylist],你可以按值删除一个元素。 还有 .RemoveAt(),用于按数组索引删除。
[System.Collections.ArrayList]$array = 'a','b','c','d','e'
$array.remove
OverloadDefinitions
-------------------
void Remove(System.Object obj)
void IList.Remove(System.Object value)
$array.remove('c')
$array
a
b
d
e
假设 $remoteFiles 是 System.IO.FileInfo 类型的文件对象。 我还假设您想根据文件名进行过滤。
$remotesumerrors = $remoteFiles.name | Select-String -Pattern '^[a-f0-9]{32}' -NotMatch
尝试使用“( )”做什么或您想要做什么查询。
编辑:根据评论更正答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.