是否有一種非 for 回圈方法可以從 arrayList 中洗掉某些專案?
$remotesumerrors = $remoteFiles | Select-String -Pattern '^[a-f0-9]{32}( )' -NotMatch
我想從 $remoteFiles var.. 中洗掉上面的輸出..是否有一些管道方法可以洗掉它們?
uj5u.com熱心網友回復:
假設以下所有情況:
- 您確實需要
$remotesumerrors單獨捕獲的結果 - 這
$remoteFiles是一個System.IO.FileInfo實體的集合,作為輸出Get-ChildItem,例如 - 將結果保存為一個總是新的集合是可以接受的
$remoteFiles,
您可以按如下方式使用.Where()陣列方法(這優于基于cmdlet 的基于管道的解決方案):Where-Object
# 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]]為獲取一組不同值(洗掉重復項)的快速便捷方法,但請注意,生成的哈希集的元素總是無序的,并且對于字串,查找默認區分大小寫- 請參閱此答案想要查詢更多的資訊。
uj5u.com熱心網友回復:
使用Where-Objectcmdlet 過濾串列:
$remoteFiles = $remoteFiles |Where-Object { $_ |Select-String -Pattern '^[a-f0-9]{32}( )' -NotMatch }
uj5u.com熱心網友回復:
如果它真的是一個 [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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/339022.html
