I want to delete objects inside of a Arraylist. Since I'm new to Powershell I found myself in quite a bit of trouble.
More Specifically I want to delete Objects inside of the first Arraylist and if the object is the same as in the second Arraylist it should get removed.
Here is what I tried so far. As a reference I tried to use this page: https://www.sapien.com/blog/2014/11/18/removing-objects-from-arrays-in-powershell/
[System.Collections.ArrayList]$everyExistingFolder = (Get-ChildItem -Path "$PSScriptRoot\test" | foreach { $_.Name })
[System.Collections.ArrayList]$everyFolderWichShouldExist = (Get-Content "$PSScriptRoot\directoriesADExport.txt")
$output = ForEach ($element in $everyExistingFolder)
{
if($element -eq $everyFolderWichShouldExist){
$everyExistingFolder.Remove($element)
}
}
Out-File $output
Is something as this possible, or did I try the wrong solution.
Would love to hear any tips or advice.
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:
$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)
}