Caligo
Caligo

Reputation: 13

deleting array content which matches with an other array

the goal of my script is to copy some files. i import a config file, which gives me the path and a filename for an exclude (the exclude shouldnt get copied).

now, i have 2 arrays, one for the folders and one for the excludes and i want to delete all rows from the array1 which contain the exclude file from array2.

i tried something like this but it has not worked...

$arrFolder = $arrFolder - $arrExcludes

or

$arrFolder | $_ -replace "$arrExcludes",""

i was searching for houres with no good solution. can anybody help me?

thank you & regards, mischa

Upvotes: 1

Views: 80

Answers (2)

Paweł Dyl
Paweł Dyl

Reputation: 9143

You can also use Except from LINQ (PS 3.0+):

$arr1 = "Folder1", "Folder2", "Folder3", "Folder4"
$arr2 = "Folder2", "Folder3"

[System.Linq.Enumerable]::Except([string[]]$arr1, [string[]]$arr2)

Upvotes: 0

woxxom
woxxom

Reputation: 73856

There are many classic and trivial loop-based solutions, for example:

$arrFolder = $arrFolder | ?{ $_ -notin $arrExcludes }

Usually, this is what you'd want, unless the arrays are very big or you do a lot of iterations.
In that case here's a different one using .NET HashSet class that works in modern PowerShell 4.0+:

$arrHash = [Collections.Generic.HashSet[string]]$arrFolder
$arrHash.ExceptWith([Collections.Generic.HashSet[string]]$arrExcludes)
$arrFolder = @($arrHash)

Upvotes: 2

Related Questions