locked
How to remove disabled users from all distribution groups - error RRS feed

  • Question

  • Hello

    I have been trying to run the following script on our AD server running Server 2012 without much success in order to remove all disabled users from all distribution groups. I have been running this from Windows Powershell ISE and have created a TEST OU with a disabled user inside

    Import-Module ActiveDirectory
    $users = Get-ADUser -Filter * -SearchBase "OU=Test,OU=Company,DC=Company,DC=local" | Where-Object {$_.Enabled -eq $False}

    foreach ($user in $users) {
     $objUser = [ADSI]"LDAP://$($user.distinguishedName)"
     $groups = $objUser.memberof
     foreach ($group in $groups) {
      $objGroup = [ADSI]"LDAP://$group"
      $objGroup.Remove $objUser
        Write-Host "$user removed from $group..."
     }
    }

    When trying to run this script I get the following error message:

    Exception calling "Remove" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
    At line:9 char:3
    +   $objGroup.Remove($objUser)
    +   ~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

    I'm not sure what I'm doing wrong here!

    Any help would be appreciated!

    J

    • Edited by JCOC2014 Thursday, October 23, 2014 3:46 PM
    Thursday, October 23, 2014 3:45 PM

Answers

All replies