Find and Delete Orphaned Alerts in SharePoint

Problem Description: In Short – When users leave your organization and removed from Active Directory (AD) they become orphans in SharePoint! Also their alerts!!

Why we care about them: To keep SharePoint clean, we’ve to remove em’ from all SharePoint sites. So, I’ve written a PowerShell script to scan all site collections of the web application, find and remove orphaned users from SharePoint here: Find and Delete Orphaned Users in SharePoint with PowerShell

Well, that solves the problem? kind of, but we have one more orphan to clean-up: SharePoint alerts created for orphaned users! Alright, Not a difficult task, Lets make use of the existing script, modify it little, run it before deleting orphaned users!

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))"
        $result = $search.FindOne()
        if ($result -ne $null)
        {
           return $true
        }
	}
	return $false  
}

#Get All site collections of all web applications
$sites = Get-SPWebApplication | Get-SPSite -Limit All
#Iterate through each site collection
foreach($site in $sites)
{
	Write-Host "Processing Site:"$site.Url -ForegroundColor Magenta
	foreach($Web in $site.AllWebs)
	{
		#Arrays to Hold Orphaned Alerts & Users
		$OrphanedAlerts = @()
		$AlertUsers  = @()
		#Get all Alerts created on the web
		$WebAlerts = $web.Alerts 
		#Get Unique Users from All Alerts 
		$AlertUsers = $web.Alerts | foreach { $_.User } | Select-Object -Unique

		#Check if any user with alerts is :Orphan!
		If($AlertUsers.length -gt 0)
		{
			foreach($AlertUser in $AlertUsers)
			{
				#Write-host "Checking User:"$AlertUser
				#Check if the user is valid - Not Orphan
				$UserName = $AlertUser.UserLogin.split("\")  #Get User Name from : Domain\UserName
				$AccountName = $UserName[1]    #UserName
					if ((CheckUserExistsInAD $AccountName) -eq $false)
                    {
						$OrphanedAlerts+=$AlertUser.Alerts
					}
			}
			if($OrphanedAlerts.Length -gt 0) 
			{ 
				Write-Host "Total No. of Orphaned Alerts Found:" $OrphanedAlerts.Length  -ForegroundColor Red
				#Delete each orphaned alert
				foreach ($OrphAlert in $OrphanedAlerts)
				{
				write-host "`nOrphaned Alert:" $OrphAlert.ID" on "$web.Url "List:" $OrphAlert.ListUrl "User:"$OrphAlert.User
				Write-Host "Deleting Orphaned Alert..."
				#$WebAlerts.Delete($OrphAlert.ID)
				}
			}
		}     
	}
}

This PowerShell script scans and deletes all alerts created for Orphaned users. Please note, I’ve commented out the line:

#$WebAlerts.Delete($OrphAlert.ID)

Just run the script to see how many alerts on what lists & libraries, Un-comment the above line by removing the # to actually remove orphaned alerts in SharePoint.

Salaudeen Rajack

Information Technology Professional with Two decades of SharePoint Experience.

One thought on “Find and Delete Orphaned Alerts in SharePoint

  • June 23, 2020 at 9:24 PM

    any idea why getting below error

    Exception calling “GetDirectoryEntry” with “0” argument(s): “Unknown error (0x80005000)”
    At line:16 char:4
    + $root = $domain.GetDirectoryEntry()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ActiveDirectoryOperationException

    Exception calling “GetDomain” with “1” argument(s): “The specified domain does not exist or cannot be contacted.”
    At line:15 char:10
    + $domain = [System.DirectoryServices.ActiveDirectory.Domain]: …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ActiveDirectoryObjectNotFoundException

    Reply

Leave a Reply