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 = ""

#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 "" $user 

1 comment:

Please Login and comment to get your questions answered!

Powered by Blogger.