#Powershell to Remove Orphaned Users from SharePoint 2013/2010
#Load SharePoint Management shell
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
#Function to Check if an 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))"
$result = $search.FindOne()
if ($result -ne $null)
{
return $true
}
}
return $false
}
#Change these variables as desired
#$WebAppURL="http://SharePointWebSite"
#$RemoveUsers = $false
#Get all Site Collections of the web application
#$WebApp = Get-SPWebApplication $WebAppURL
$textout = ""
$textout > "D:\SPO\SharePointOrphanedUsers.csv"
$Farm = Get-SPWebApplication
Foreach ($WebApplicationname in $Farm)
{
$WebApp = Get-SPWebApplication -identity $WebApplicationname
$WebAppSites = $WebApp.Sites
#Iterate through all Site Collections
foreach($site in $WebApp.Sites)
{
if ($site -ne $null)
{
$web = $site.AllWebs
foreach ($webp in $web)
{
$OrphanedUsers = @()
if (($webp.permissions -ne $null) -and ($webp.hasuniqueroleassignments -eq "True"))
{
#Iterate through the users collection
foreach($User in $webp.SiteUsers)
{
#Exclude Built-in User Accounts , Security Groups & an external domain "corporate"
if(($User.LoginName.ToLower() -ne "nt authority\authenticated users") -and
($User.LoginName.ToLower() -ne "nt authority\system") -and
($User.LoginName.ToLower() -ne "sharepoint\system") -and
($User.LoginName.ToLower() -ne "nt authority\local service") -and
($user.IsDomainGroup -eq $false ) -and
($User.LoginName.ToLower().StartsWith("corporate") -ne $true) )
{
$UserName = $User.LoginName.split("\") #Domain\UserName
$AccountName = $UserName[1] #UserName
#If the user does not exist in Active Directory then it is an orphaned account in the SharePoint Site Collection
if ( ( CheckUserExistsInAD $AccountName) -eq $false )
{
$textout = """$($User.Name)"",""$AccountName"",""($($User.LoginName))"",""$($webp.URL)"""
#Write-Host $textout
$textout >> "D:\SPO\SharePointOrphanedUsers.csv"
#Make a note of the Orphaned user
$OrphanedUsers+=$User.LoginName
}
}
}
# **** Remove Users ****#
# Remove the Orphaned Users from the site
# if ($RemoveUsers)
#{
# foreach($OrpUser in $OrphanedUsers)
#{
# $webp.SiteUsers.Remove($OrpUser)
# Write-host "Removed the Orphaned user $($OrpUser) from $($webp.URL) "
#}
# }
}
}
}
}
}



No comments:
Post a Comment