Thursday, June 28, 2012

Mysite Creation using Powershell


Before making the sharepoint site live ,in certain cases, we would like to create mysites beforehand for the users so that there wouldn't be too much load on the servers when thousands of user access the site to create their personal sites. We can automatically create mysites using powershell without having the user visit their site.

For our requirement, we had to create mysites for a set of over hundred users when the site was made live for each domain hence the script was run in batch. The approach taken were we uploaded a file containing a list of user accounts-domain\username(delimited with “,”) to a sharepoint site ; the script would read from this file and create mysite for each of these accounts. And finally , a log file was uploaded back to the site with the report of how many mysites were created and how many failed.

Script to create mysite (Mysite.ps1) :
param([string]$webUrl,[string]$docLibName,[string]$textFileName,[string]$logFileName)
function HelpText
{
   write-host ""
   write-host "  Usage:"
   write-host ""
   write-host ".\Mysite.ps1 -webUrl [webUrl] -docLibName [docLibName] -textFileName [textFileName] -logFileName [logFileName]"
   write-host ""
   write-host "  webUrl:Url of the site where list of domain\username accounts file is uploaded"
   write-host "  docLibName:Name of the Document Library where the file is uploaded."
   write-host "  textFileName:The Text FileName which consists the list of user accounts"
   write-host "  logFileName:The name of the log file"      
   write-host ""
   exit
}
if (($webUrl -eq "") -or ($docLibName -eq "") -or ($textFileName -eq "") -or ($logFileName -eq ""))
{
       HelpText 
}
$snap = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snap -eq $null) {
  Add-PSSnapin Microsoft.SharePoint.Powershell
}

##declarations##
$fileToUpload = "C:\$logFileName";
$totalUsers = 0
$totalMysiteCreated=0
$totalUserNotExists=0

##Create a new File for logs##
$fileStream = new-object System.IO.FileStream($fileToUpload, [System.IO.FileMode]::Create,[System.IO.FileAccess]::Write);
trap [Exception]
{
 write-host "Error creating file $fileToUpload .ERROR MESSAGE>>>$($_.Exception.Message)" -ForeGroundColor Red
 break
}
$fileName = [System.IO.Path]::GetFileName($fileToUpload);
$sw = new-object System.IO.StreamWriter($fileStream);

##Get web,document library ,file##
$spweb=Get-SPWeb -Identity $webUrl
$spFolder = $spWeb.GetFolder($docLibName)
$spFile =$spFolder.Files[$textFileName]
write-host Got Text File $textFileName -ForeGroundColor Green

##Get the userprofile manager ##
$serviceCtxt=Get-SPServiceContext -Site $spweb.Site
$upManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceCtxt);

##Read Textfile consisting of user accounts##
$sr=new-object System.IO.StreamReader($spFile.OpenBinaryStream())
$filecontent = $sr.ReadToEnd();
$tpxids = $filecontent.Split(',');
foreach ($tpxid in $tpxids)
{
 $totalUsers=$totalUsers+1
 if($upManager.UserExists($tpxid))
 {
  $script:success=$true
  write-host Creating Mysite For $tpxid -ForeGroundColor Green

       ##Get UserProfile and Create Mysite##
       $profile = $upManager.GetUserProfile($tpxid);
       $profile.CreatePersonalSite();
       trap [Microsoft.Office.Server.UserProfiles.PersonalSiteExistsException] 
        {       
          $script:success=$false       
          write-host "Mysite Already Exists for $tpxid." -ForeGroundColor red
          $sw.WriteLine("$(get-date)::Mysite Already Exists for $tpxid.");
          continue     
        } 
  trap [Exception]
  {
   $script:success=$false 
   write-host "Error creating MySite for $tpxid.ERROR MESSAGE>>>$($_.Exception.Message)" -ForeGroundColor red
   $sw.WriteLine("$(get-date)::Error creating MySite for $tpxid.ERROR MESSAGE>>>$($_.Exception.Message)>>>$($_.Exception.InnerException)");                       
   continue
  }
  if($script:success -eq $true)
  {
   write-host "Created MySite Successfully For $tpxid" -ForeGroundColor green
   $sw.WriteLine("$(get-date)::Created MySite Successfully For $tpxid");
   $totalMysiteCreated=$totalMysiteCreated+1
  }         
 }
 else 
 {
  write-host "User doesnt exist $tpxid" -ForeGroundColor red
  $sw.WriteLine("$(get-date):::::User doesnt exist $tpxid");
  $totalUserNotExists=$totalUserNotExists+1
 }

}
$sw.WriteLine("Total Users: $totalUsers      Total MySite Created:$totalMysiteCreated       Total User Doesnt Exists:$totalUserNotExists");
$sw.Close();
$fileStream.Close();

##Upload Log File to Document Library##
$spFolder.Files.Add($fileName, [System.IO.File]::OpenRead($fileToUpload),$true);
$spFolder.Update();
$spweb.Dispose();
write-host Completed ...


To run the script enter the full path to the script (c:\scripts\Mysite.ps1) or if its in the current directory (.\Mysite.ps1).
Example:
.\Mysite.ps1 -webUrl “http://<sharepointsite>” -docLibName “MyLibrary” -textFileName “myfile.txt” -logFileName “logfile.txt”

If you want to create a mysite for all the existing user profiles , use “$AllUserProfiles = $upManager.GetEnumerator()” and loop through $AllUserProfiles to create mysites.


No comments:

Post a Comment