Find Orphan User E-mails in List Items using PowerShell

Requirement:
Our customized application for sending newsletters organizational-wide keeps its list of users to send email in a SharePoint list called “Subscriptions”. Users are configured in a people picker field of the list. Now, when someone leaves the organization, their account becomes an orphan, and their Emails also go invalid.

So prior to processing the Emails column, we had to scan the people picker column in the list for orphaned user Emails.

PowerShell script to scan for orphaned Users from their Emails:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Import-Module ActiveDirectory
 
$Web= Get-SPWeb "https://portal.crescent.com/News/"
$List = $Web.Lists["Subscriptions"]
$FieldName="Members"

foreach($item in $List.Items)
{
  if($Item[$FieldName] -ne $null)
  {
   #Get People picker field values collection
   $UserCollection = New-Object Microsoft.Sharepoint.SPFieldUserValueCollection($Web,$Item[$FieldName].ToString())
         
        #Get each User from the Person or Group field
        foreach($UserObj in $UserCollection)
        {
            #Try to get the user from AD from Email 
            $ADUser= Get-ADUser -Filter {mail -eq $UserObj.User.Email}
          
            #check if user email doesn't exist in AD
            if($ADUser -eq $null)
             {
                "https://portal.crescent.com/News/Pages/ViewUser.aspx?UserId=$($Item['ID'])" + $UserObj.User.LoginName + $UserObj.User.Email
             }
        }
    }
}

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *