Sunday 21 April 2013

To find users existence in both SharePoint & Active Directory (AD)


                  In the last week, we got a problem over SharePoint User Profile Sync Service some user details are not ported properly, or missing from AD. Hence, we have users, with partially updated details so need to list those users, for this we could use this handy power shell script.


[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")
clear;
$siteUrl = Read-Host "Enter the User Profile Url :: ";
$site = new-object Microsoft.SharePoint.SPSite($siteUrl);
$sw = New-Object System.IO.StreamWriter("D:\\ProfileDetails.txt");
$sw.WriteLine("User Profile Url :: "+$site.Url);
Write-Host "User Profile Url :: " $site.Url;
$sc = [Microsoft.Office.Server.ServerContext]::GetContext($site);
Write-Host "Status", $sc.Status;
$sw.WriteLine("Status :: "+$sc.Status);
$userProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($sc);
Write-Host "Total Users : " $userProfileManager.Count;
$sw.WriteLine("Total Users :: "+$userProfileManager.Count);
$enumerator = $userProfileManager.GetEnumerator();
$totalUserCount = 0;
while( $enumerator.MoveNext() -eq $true )
{
 $currentUserProfile = $enumerator.Current;
  $propertiesCollection = $currentUserProfile.ProfileManager.PropertiesWithSection;
  $userid = $null;
  if( $currentUserProfile -ne $null -and $propertiesCollection -ne $null )
  {
    $userid = $usrid = $currentUserProfile["AccountName"].tostring().split("\")[1];
[string]$usrName = "FirstName :: " + $currentUserProfile["FirstName"].toString() + " LastName :: " + $currentUserProfile["LastName"].toString();
$userName = $currentUserProfile["PreferredName"].toString();
    Write-Host "User Id :: " $usrid " User Name :: " $userName;
Write-Host $usrName;

$sw.WriteLine("User Id :: "+$usrid+" User Name :: "+$userName);
$sw.WriteLine($usrName);    
$objSite = new-object Microsoft.SharePoint.SPSite($siteUrl)
$objWeb = $objSite.OpenWeb();
try
{
$byUser = $objWeb.EnsureUser($usrid);
Write-Host $userid " exists both in AD & SharePoint" -ForegroundColor Green;
$sw.WriteLine($userid+" exists both in AD & SharePoint");
}Catch [System.Exception]
{
Write-Host $userid " doesn't exist in AD or SharePoint" -ForegroundColor Red;
$sw.WriteLine($userid+" doesn't exists in AD or SharePoint");
}
  }
}
$sw.Close();

Idea Behind:

Use ensureUser() method which will uses the following steps to ensure a user :
     1. Its first checks the User's ID from AD
     2. Get SPPrincipalInfo from Web App.
     3. If the SPPrincipalInfo from step 2 is null, try to get the user instance from AD again, Get the SPPrincipalInfo from AD (GC).

If any step fails, ensureUser will throw "Specified User Cannot be found".

Happy Coding :)



No comments:

Post a Comment