Friday, January 16, 2015

Recover and Restore SharePoint Group Users

Context: SharePoint Owner of a site accidently deleted the ‘Members’ group and wanted the group with all users back.

Solution: First I restored the backup of the Content database in the Test environment and mounted it to the Web Application. 
Once the Site collection is available, I wrote a PowerShell Script to export the Users of the ‘members’ Group into Csv file. The following is the code that I wrote;

clear

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

$siteUrl = "https://test.sharepoint.group/sites/1112"
$csvPath = "C:\Users\salman\Desktop\Export Csv\UsersRetrieved.csv"

$site = Get-SPSite $siteUrl

$group = $site.RootWeb.SiteGroups.GetByName("Site_Member");

$userList = @()
foreach($user in $group.Users)
{
    $psUser = New-Object PSObject -Property @{
        "ID" = $user.ID
        "Display Name" = $user.DisplayName
        "Login Name" = $user.LoginName
        
    }
    $userList += $psUser;
}

if($userList.length -gt 0)
{
    $userList | Export-Csv -Path $csvPath
    Write-Host "Total Users exported: " $group.Users.Count;
}

$site.Dispose();



Then, I created a group named as Site_Members manually by looking at the settings from the testing environment site group.

Once the group is ready, I copied the csv file created with the Import script in the Production environment and ran the following PS script in the production environment.

clear

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

$siteUrl = "https://sharepoint.group/sites/1112"
$csvPath = "C:\Users\salman\Desktop\Export Csv\UsersRetrieved.csv";
$groupName = "Site_Member";

$site = Get-SPSite $siteUrl

$group = $site.RootWeb.Groups.GetByName("$groupName");
if(Test-Path $csvPath)
{
    $usersList = Import-Csv -Path $csvPath
    foreach($user in $usersList)
    {
        $name = $user."Login Name";        
        $user = $site.RootWeb.EnsureUser($name)        
        $group.AddUser($user);
    }    
}

No comments:

Post a Comment