I have two array which I like to compare to remove or add name to file
for example
$oldArray= @“a”, “b”, “c”
$newarray=@“a”, “b”, “d”, “e”
I would like to compare both array and add d & e but remove c because c doesnt existed in new array
$oldArray= @(“a”, “b”, “c”)
$newarray=@(“a”, “b”, “d”, “e”)
foreach ($a in $oldArray) {
if ($newarray -contains $a)
{ “Doesnt existed in new array so lets add it” }
}
I got this which is working but is it better way to do it
$oldArray= @(“a”, “b”, “c”)
$newarray=@(“a”, “b”, “d”, “e”)
Compare-Object -IncludeEqual -ReferenceObject $oldArray -DifferenceObject $newarray | Where-Object -FilterScript {
if($.SideIndicator -eq “=>”){Write-Host "New Object - " $.InputObject}
if($.SideIndicator -eq “<=”){Write-Host "Remove Object - " $.InputObject}
}
Compare being the key word, look at Compare-Object:
$oldArray= @(“a”, “b”, “c”,"f","g")
$newarray=@(“a”, “b”, “d”, “e”)
#compare the arrays, anything <= is NOT in $newArray
$compArray = Compare-Object -ReferenceObject $oldArray -DifferenceObject $newarray
#create an array of items that is NOT in $newArray
$stuffToRemove = $compArray | Where {$_.SideIndicator -eq '<='} | Select-Object -ExpandProperty InputObject
#Filter all of the $stuffToRemove from $oldArray
$oldArrayUpd = $oldArray | Where{$stuffToRemove -notcontains $_}
$oldArrayUpd
Output:
PS C:\Users\rasim> $compArray
InputObject SideIndicator
----------- -------------
d =>
e =>
c <=
f <=
g <=
PS C:\Users\rasim> $stuffToRemove
c
f
g
PS C:\Users\rasim> $oldArrayUpd
a
b
And another option.
$oldArray= @(“a”, “b”, “c”)
$newarray=@(“a”, “b”, “d”, “e”)
$ItemsToAdd = $newarray.Where({$_ -notin $oldArray})
$itemsToRemove = $oldArray.where({$_ -notin $newarray})
Output
PS C:\> $ItemsToAdd
d
e
PS C:\> $itemsToRemove
c