[英]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.