Remove User from All Sites in SharePoint using PowerShell
How to delete a user from all site collections in SharePoint 2013 using PowerShell?
Sometimes, we may need to delete a particular user from all site collections. Say for e.g., an 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 a 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 "https://sharepoint.crescent.com" $user
}
it does not work,not delete any user