0

Having recently upgraded my workstation to Windows10 I've been checking all my old scripts and it seems that IndexOf is behaving differently.

In PS4 this worked fine:

    $fullarray = $permissions | %{
    $obj = new-object psobject
    $obj | add-member -name Group -type noteproperty -value $_.Account.AccountName
    $obj | add-member -name Access -type noteproperty -value $_.AccessRights
    $obj
}   
$array = {$fullarray}.Invoke()
# Convert array to list from which we can remove items
$arraylist = [System.Collections.ArrayList]$array
# Remove admin groups/users
$ExcludeList | % {
    $index = ($arraylist.group).IndexOf($_)
    If ($index -gt -1) {
        $arraylist.RemoveAt($index) | Out-Null
    }
}

However in PS5 the IndexOf just returns -1 for all values. I couldn't find a way to get it work with arraylists at all - to get that to work in PS5 now I have this kludge fix:

    $array = {$fullarray}.Invoke()
# Convert array to list from which we can remove items
$arraylist = [Collections.Generic.List[Object]]($array)
# Remove admin groups/users
ForEach ($HideGroup in $ExcludeList) {
    $index = $arraylist.FindIndex( {$args[0].Group -eq $HideGroup} )
    If ($index -gt -1) {
        $arraylist.RemoveAt($index) # | Out-Null
    }
}

Any idea on why this has changed, and if you have a better fix that would be much appreciated!

Scepticalist
  • 3,737
  • 1
  • 13
  • 30

1 Answers1

1

I don't know the answer to why you see different behaviors with ArrayList.IndexOf(), but I would suggest using Where-Object instead of what you are doing:

$fullarray = $permissions | ForEach-Object {
    $obj = new-object psobject
    $obj | add-member -name Group -type noteproperty -value $_.Account.AccountName
    $obj | add-member -name Access -type noteproperty -value $_.AccessRights
    $obj
} 
$filteredarray = $fullarray | Where-Object { $Excludelist -notcontains $_.Group }
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Good shout. The script was along time in evolution and I think I originally changed to an ArrayList as I also wanted to remove based on other criteria (such as if a user was member already) and add also an item once I'd removed the unwanted groups, but I can see it might still be simpler to use this method. Thanks – Scepticalist Apr 14 '16 at 11:42
  • You could do that with `Where-Object` as well – Mathias R. Jessen Apr 14 '16 at 14:47