SimonS SimonS - 3 months ago 19
PowerShell Question

delete objects from array when their path property equals object in another array

I have an

$array
of
PSCustomObjects
which contain a path,days,filter and recurse property

I
Test-Path
the path of each
PSCustomObject
and if it's
false
, I save only the path in another variable like
$failpath


Now I want to remove all Objects inside
$array
when the path is inside
$failpath


I tried things like the
.remove()
method for the
$array
, but that doesn't work and gave me this error (example pic from web): https://i0.wp.com/www.sapien.com/blog/wp-content/uploads/2014/11/image8.png

So I tried creating a new array, but it's giving me a hard time because I don't know how to iterate over the failpaths correctly. so that each correct objects only gets sent to the new array once (when I tried it, the correct object was there multiple times) - i can't show you the code for this because I already edited it too many times and now it's just a mess.

this is how
$array
and
$faultypath
look like

$array = @(
[pscustomobject]@{
path = "\\server\daten\Alle Adressen\Dokumente 70"
filter = "*.pdf"
days = "90"
recurse = "false"
}
[pscustomobject]@{
path = "\\server\Tobit\itacom\ERP2UMS"
filter = "*.fax"
days = "7"
recurse = "false"
}
)

[string[]]$faultypath = @()
$pfade | % { if (!(Test-Path $_.path)) { $faultypath += $_.path } }


How can I substract everything which is in
$faultypath
from
$array
?

Answer

For PowerShell 3 or higher

$faultyPath = $pfade | Where-Object { -not (Test-Path $_.Path) } | ForEach-Object Path
$array | Where-Object Path -notin $faultyPath

For PowerShell 2 or lower

$faultyPath = $pfade | Where-Object { -not (Test-Path $_.Path) } | ForEach-Object { $_.Path }
$array | Where-Object { $faultyPath -notcontains $_.Path }

This is potentially an expensive array comparison if both sets are large. In that case dictionaries or hashtables will provide better performance for the comparison.

Comments