Home > Enterprise >  Powershell Remove objects from an array list
Powershell Remove objects from an array list

Time:10-28

Is there a non for-loop way to remove some items from a arrayList?

$remotesumerrors = $remoteFiles | Select-String  -Pattern '^[a-f0-9]{32}(  )' -NotMatch

I want to remove the output of the above from the $remoteFiles var.. is there some pipe way to remove them?

CodePudding user response:

Assuming all of the following:

  • you do need the results captured in $remotesumerrors separately
  • that $remoteFiles is a collection of System.IO.FileInfo instances, as output by Get-ChildItem, for instance
  • it is acceptable to save the result as an invariably new collection back to $remoteFiles,

you can use the .Where() array method as follows (this outperforms a pipeline-based solution based on the 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) })

As an aside:

  • Casting a collection to [System.Collections.Generic.HashSet[T]] is a fast and convenient way to get a set of distinct values (duplicates removed), but note that the resulting hash set's elements are invariably unordered and that, with strings, lookups are by default case-sensitive - see this answer for more information.

CodePudding user response:

Use the Where-Object cmdlet to filter the list:

$remoteFiles = $remoteFiles |Where-Object { $_ |Select-String -Pattern '^[a-f0-9]{32}(  )' -NotMatch }

CodePudding user response:

If it truly was a [collections.arraylist], you could remove an element by value. There's also .RemoveAt(), to remove by array index.

[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
  • Related