Saturday, February 28, 2015

Remove User From All Sites in SharePoint using PowerShell

Delete user from all site collections in SharePoint 2010/2013 using PowerShell:
Some times, we may need to delete a particular user from all site collections. Say for e.g. Employee leaves the company! Here is how to remove a user from all SharePoint sites using PowerShell.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Function Delete-UserFromAllSites([string]$WebAppURL, [string]$UserID)
{
    #Get All Site collections
    $SitesColl = Get-SPWebApplication $WebAppURL | Get-SPSite -Limit All

    foreach($Site in $SitesColl)
    {
        write-host "Processing site:" $Site.RootWeb.URL
        
        #Check if user Exists in the site collection
        $User = $Site.RootWeb.SiteUsers | Where-Object {$_.LoginName -eq $UserID}
           
        #If user account found
        if($User -ne $null)
        {
            #Remove User from the Site
            Remove-SPUser $UserID -web $Site.RootWeb.URL -confirm:$false
            write-host "Removed user from site collection:"$Site.RootWeb.URL -f Green
        }        
    }    
}

#Variables for processing
$WebAppURL = "https://Portal.Crescent.com/"
$UserID="Crescent\DaveP"

#Call the function
Delete-UserFromAllSites $WebAppURL $UserID
 
This will scan and delete SharePoint user from all site collections in the given web application.

To delete multiple users from all site collections, just store user accounts in an array and call the PowerShell function. E..g
#Array to store user accounts
$userNames= ("domain\user1", "global\user2", "domain\user3")
#Iterate through the array
foreach($user in $userNames)
 {  
   #Call the function
   Delete-UserFromAllSites "http://sharepoint.crescent.com" $user 
 }



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...