Home > database >  Powershell script skipping some users
Powershell script skipping some users

Time:04-08

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 { }
        }

CodePudding user response:

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
    }
}
  • Related