I have 5 SP Groups and it has 50+ orphan users that I need to remove from this groups (I dont want to use remove-spsuser). I just need to clean up the SharePoint groups.

Is there any powershell way to do to go through all the SharePoint groups for a site collection and remove in-active or orphan users?

1 Answer 1


Here is the code that worked.

# https://www.sharepointdiary.com/2013/12/find-and-delete-orphaned-alerts-in-sharepoint.html
# https://www.sharepointdiary.com/2015/10/remove-user-from-sharepoint-group-using-powershell.html

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Function to Check if a User exists in AD
function CheckUserExistsInAD()
    Param( [Parameter(Mandatory=$true)] [string]$UserLoginID )  
    #Search the User in AD
    $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
    foreach ($Domain in $forest.Domains)
        $context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $Domain.Name)
        $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)
        $root = $domain.GetDirectoryEntry()
        $search = [System.DirectoryServices.DirectorySearcher]$root
        $search.Filter = "(&(objectCategory=User)(samAccountName=$UserLoginID)(userAccountControl=512))"
        $result = $search.FindOne()
        if($result -ne $null)
            return $false
            write-host $UserLoginID
        return $true
        write-host $UserLoginID
#Function RemoveUser-FromAllGroups($SiteURL)
     #Get the Web
     #$web=Get-SPWeb $SiteURL
     $web = get-spweb "https://inside.myNOV.com/sites/OracleUpgrade"
     #Get the User to Remove 
     #$User  = $Web.EnsureUser($UserAccount)
     #Iterate through all Groups
     foreach($Group in $Web.Groups)
     #write-host $group.Name
         foreach($user in $group.users)
            #Exclude Built-in User Accounts , Security Groups
            if(($User.LoginName.ToLower() -ne "nt authority\authenticated users") -and($User.LoginName.ToLower() -ne "sharepoint\system") -and($User.LoginName.ToLower() -ne "nt authority\local service") -and($user.IsDomainGroup -eq $false ) )
                #write-host $user
                $UserName = $user.LoginName.split("\")  #Domain\UserName
                $AccountName = $UserName[1]    #UserName         
                #write-host $AccountName
                if((CheckUserExistsInAD $AccountName) -eq $true)
                    write-host $group.Name "  -  "   $user.Name " not active"

 #Call the function to remove user from all groups in the site  
 #RemoveUser-FromAllGroups "https://inside.myNOV.com/sites/OracleUpgrade" 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.