Tony
Tony

Reputation: 9581

Powershell Remove objects from an array list

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?

Upvotes: 1

Views: 3808

Answers (4)

Aaron
Aaron

Reputation: 573

Let assume that $remoteFiles is a file object of type System.IO.FileInfo. I also assume that you want to filter based on filename.

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

What are trying to do with "( )" or what is query that you want to do.

edit: corrected answer based on comment

Upvotes: 0

js2010
js2010

Reputation: 27473

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

Upvotes: 1

mklement0
mklement0

Reputation: 438153

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.

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174545

Use the Where-Object cmdlet to filter the list:

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

Upvotes: 0

Related Questions