I'm assuming you're doing this to get a list of folders that needs to be created. Even though removing from ArrayList is totally possible, what you're trying to do in this case is not. You cannot modify a collection while it is being enumerated as far as I know.
The reason why you're not getting any error is because of your use of the equality operator -eq, if you need to find an element in a collection you need to use a containment operator instead (-in or -contains in this case).
Here are the steps to reproduce the exception you would have gotten if the code was right:
using namespace System.IO
using namespace System.Collections
$foldersExisting = 'Folder1', 'Folder2', 'Folder3', 'Folder4', 'Folder5'
$foldersFromFile = 'Folder2', 'Folder4', 'Folder6', 'Folder7'
[ArrayList]$listExisting = [FileInfo[]]$foldersExisting
[ArrayList]$listFromFile = [FileInfo[]]$foldersFromFile
foreach($folder in $listExisting)
{
if($folder.Name -in $listFromFile.Name)
{
$listExisting.Remove($folder)
}
}
Above code would throw the following Exception:
Collection was modified; enumeration operation may not execute.
As for what you're trying to accomplish ($everyExistingFolder should contain those elements that are not found on $everyFolderWichShouldExist), you should filter the first array based on the elements of the second array:
PS/> $foldersExisting.where({ $_ -notin $foldersFromFile })
Folder1
Folder3
Folder5
In case you really need to remove the items from the first collection you can do so this way, first filter the elements to remove and then loop over them. The result from this would be the same as the filtering technique displayed above.
foreach($folder in $listExisting.Where({ $_.Name -in $listFromFile.Name }))
{
$listExisting.Remove($folder)
}
PS /> $listExisting
UnixMode User Group LastWriteTime Size Name
-------- ---- ----- ------------- ---- ----
12/31/1600 20:07 Folder1 ->
12/31/1600 20:07 Folder3 ->
12/31/1600 20:07 Folder5 ->