0

I have the following script that should run through all identities from Sailpoint IdentityIQ, and remove the membership, but it randomly don't affect users, we saw in the logs that it process one user correctly and then the next one starts but the script then start with the next user not updating the one before.

Can we add a lock or retry until it's done?

Here's the code we already have.

Thank you!

    $ADgroups = Get-ADPrincipalGroupMembership -Identity $adUser | where {$_.Name -ne "Domain Users"}
        if ($ADgroups -ne $null){
          try{
            Remove-ADPrincipalGroupMembership -Identity $adUser -MemberOf $ADgroups -Confirm:$false
            wlog  "info"  "Removed all assigned AD groups." $mainfn
          } catch { }
        }
jmpg85
  • 15
  • 4
  • why are you using try/catch instead of for-each? – another victim of the mouse Apr 06 '22 at 19:28
  • 1
    Try with `if (@($ADgroups).Count) { .. }` and add `-ErrorAction Stop` to the `Remove-ADPrincipalGroupMembership` line if you want to catch exceptions (also non-terminating ones). Inside the catch I would also log the error in `$_.Exception.Message` – Theo Apr 06 '22 at 19:59
  • HI thank you for your responses, they created this script before I started working with them and found out that sometimes it fails, no errors, just seems to skip the user. I will test this and let you know. – jmpg85 Apr 06 '22 at 20:59
  • As Theo notes, the script generates no errors because your __`catch` block is empty__ – Santiago Squarzon Apr 06 '22 at 22:18

1 Answers1

0

As already commented, your current code does not output errors, because you do nothing in the catch block. Also, by not specifying -ErrorAction Stop, not all errors will make the code execute whatever is in the catch block..

Try

# assuming the variable $adUser is a valid AD object or the DistinguishedName, GUID, SID or SamAccountName
$ADgroups = Get-ADPrincipalGroupMembership -Identity $adUser | Where-Object {$_.Name -ne "Domain Users"}
# force $ADgroups to be an array here so you can use its .Count property
if (@($ADgroups).Count) {
    try {
        # append ErrorAction STop to also capture non-terminating errors in the catch block
        Remove-ADPrincipalGroupMembership -Identity $adUser -MemberOf $ADgroups -Confirm:$false -ErrorAction Stop
        # log success
        wlog  "info"  "Removed all assigned AD groups." $mainfn
    } 
    catch { 
        # log error
        wlog  "error"  $_.Exception.Message $mainfn
    }
}
Theo
  • 57,719
  • 8
  • 24
  • 41
  • Hi it worked as expected! However they now want to run it in a different way. Thank you very much for your help! – jmpg85 Apr 07 '22 at 21:46